PATINDEX Expression











up vote
-1
down vote

favorite
2












I'm creating a patindex:



Character 1 must be Alpha and Not space, and the remaining characters should contain any A-Z,a-z,space or '-



 patindex('^ [A-Z]%[A-Za-z '-]','Worktester')


But this doesn't seem to work



It seems PATINDEX() doesn't allow this kind of pattern matching.



Can you please advise if this is correct or any links which can help on the expression?



Thank you










share|improve this question
























  • Are you trying to validate a string or locate a substring that meets the requirements?
    – HABO
    Nov 19 at 18:13















up vote
-1
down vote

favorite
2












I'm creating a patindex:



Character 1 must be Alpha and Not space, and the remaining characters should contain any A-Z,a-z,space or '-



 patindex('^ [A-Z]%[A-Za-z '-]','Worktester')


But this doesn't seem to work



It seems PATINDEX() doesn't allow this kind of pattern matching.



Can you please advise if this is correct or any links which can help on the expression?



Thank you










share|improve this question
























  • Are you trying to validate a string or locate a substring that meets the requirements?
    – HABO
    Nov 19 at 18:13













up vote
-1
down vote

favorite
2









up vote
-1
down vote

favorite
2






2





I'm creating a patindex:



Character 1 must be Alpha and Not space, and the remaining characters should contain any A-Z,a-z,space or '-



 patindex('^ [A-Z]%[A-Za-z '-]','Worktester')


But this doesn't seem to work



It seems PATINDEX() doesn't allow this kind of pattern matching.



Can you please advise if this is correct or any links which can help on the expression?



Thank you










share|improve this question















I'm creating a patindex:



Character 1 must be Alpha and Not space, and the remaining characters should contain any A-Z,a-z,space or '-



 patindex('^ [A-Z]%[A-Za-z '-]','Worktester')


But this doesn't seem to work



It seems PATINDEX() doesn't allow this kind of pattern matching.



Can you please advise if this is correct or any links which can help on the expression?



Thank you







sql sql-server tsql






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 20 at 21:06









LukStorms

11k31532




11k31532










asked Nov 19 at 16:19









user3687828

65




65












  • Are you trying to validate a string or locate a substring that meets the requirements?
    – HABO
    Nov 19 at 18:13


















  • Are you trying to validate a string or locate a substring that meets the requirements?
    – HABO
    Nov 19 at 18:13
















Are you trying to validate a string or locate a substring that meets the requirements?
– HABO
Nov 19 at 18:13




Are you trying to validate a string or locate a substring that meets the requirements?
– HABO
Nov 19 at 18:13












3 Answers
3






active

oldest

votes

















up vote
1
down vote













Sometimes the trick to using pattern matching is to find bad, rather than good, patterns. To validate a string of unknown length (rather than extract a substring) you can search for the patterns of unacceptable characters:



declare @Samples as Table ( Sample VarChar(16) );
insert into @Samples ( Sample ) values
( 'Worktester' ), ( 'Foo Bar' ), ( 'Voot-Plex' ),
( 'BR549' ), ( ' Spaced Out' ), ( 'low down' ), ( 'Oops!' );

select Sample,
-- Check the first character for uppercase alpha only.
PatIndex( '[^A-Z]%', Sample collate Latin1_General_BIN ) as Part1,
-- Check the remaining characters for any mix of alpha, space and hyphen.
PatIndex( '_%[^-A-Za-z ]%', Sample collate Latin1_General_BIN ) as Part2,
-- Put it together into a single status.
case
when PatIndex( '[^A-Z]%', Sample collate Latin1_General_BIN ) = 0 and
PatIndex( '_%[^-A-Za-z ]%', Sample collate Latin1_General_BIN ) = 0 then 'Good'
else 'Bad' end as Status
from @Samples;


Note that the default collation tends to be case-insensitive. Try changing the Part1 line by removing the explicit collation.






share|improve this answer




























    up vote
    0
    down vote













    Could you try this one



    patindex('[A-Z]%[A-Za-z ''-]%','Worktester')





    share|improve this answer





















    • The % wildcards will accept any characters, hence it won't filter out "My bad!" for ending in a bang.
      – HABO
      Nov 19 at 18:00










    • Thank you, It works
      – user3687828
      Nov 20 at 9:22










    • @jigga: If my title is set as "M R" with space in between. when using Ltrim(Rtrim(Title)), this is not returning "MR"
      – user3687828
      Nov 20 at 11:36










    • @user3687828 so you want all the spaces to be removed? I thought you wanted the first space to be filtered out
      – jigga
      Nov 22 at 18:04


















    up vote
    0
    down vote













    Using PATINDEX for pattern matching can be a pain.



    Since the pattern syntax for LIKE or PATINDEX is way more limited than for Regexp.



    If it's just to filter out those with other characters, you could use a LIKE instead of PATINDEX.

    Since they uses the same syntax, and you don't need to know the position for this.



    And it seems you just have to check if the first character is a letter, and if it doesn't contain anything other than letters, space, quotes or dash.



    declare @Table table (
    ID int identity(1,1) primary key,
    Col varchar(30) not null,
    IsValid bit
    );

    insert into @Table (col, isValid) values
    ('Foobar',1), ('Foo-''Bar''',1), ('foo bar',1),
    (' Foo',0), ('F0ob4r',0), ('Foo?',0);

    SELECT *
    FROM @Table
    WHERE Col LIKE '[a-z]%'
    AND Col NOT LIKE '%[^a-z ''-]%';


    Result: Those with isValid = 1



    Or use it in a CASE



    SELECT *,
    (CASE
    WHEN Col LIKE '[a-z]%' AND Col NOT LIKE '%[^a-z ''-]%'
    THEN 1
    ELSE 0
    END) AS isOk
    FROM @Table;





    share|improve this answer























      Your Answer






      StackExchange.ifUsing("editor", function () {
      StackExchange.using("externalEditor", function () {
      StackExchange.using("snippets", function () {
      StackExchange.snippets.init();
      });
      });
      }, "code-snippets");

      StackExchange.ready(function() {
      var channelOptions = {
      tags: "".split(" "),
      id: "1"
      };
      initTagRenderer("".split(" "), "".split(" "), channelOptions);

      StackExchange.using("externalEditor", function() {
      // Have to fire editor after snippets, if snippets enabled
      if (StackExchange.settings.snippets.snippetsEnabled) {
      StackExchange.using("snippets", function() {
      createEditor();
      });
      }
      else {
      createEditor();
      }
      });

      function createEditor() {
      StackExchange.prepareEditor({
      heartbeatType: 'answer',
      convertImagesToLinks: true,
      noModals: true,
      showLowRepImageUploadWarning: true,
      reputationToPostImages: 10,
      bindNavPrevention: true,
      postfix: "",
      imageUploader: {
      brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
      contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
      allowUrls: true
      },
      onDemand: true,
      discardSelector: ".discard-answer"
      ,immediatelyShowMarkdownHelp:true
      });


      }
      });














      draft saved

      draft discarded


















      StackExchange.ready(
      function () {
      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53378762%2fpatindex-expression%23new-answer', 'question_page');
      }
      );

      Post as a guest















      Required, but never shown

























      3 Answers
      3






      active

      oldest

      votes








      3 Answers
      3






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes








      up vote
      1
      down vote













      Sometimes the trick to using pattern matching is to find bad, rather than good, patterns. To validate a string of unknown length (rather than extract a substring) you can search for the patterns of unacceptable characters:



      declare @Samples as Table ( Sample VarChar(16) );
      insert into @Samples ( Sample ) values
      ( 'Worktester' ), ( 'Foo Bar' ), ( 'Voot-Plex' ),
      ( 'BR549' ), ( ' Spaced Out' ), ( 'low down' ), ( 'Oops!' );

      select Sample,
      -- Check the first character for uppercase alpha only.
      PatIndex( '[^A-Z]%', Sample collate Latin1_General_BIN ) as Part1,
      -- Check the remaining characters for any mix of alpha, space and hyphen.
      PatIndex( '_%[^-A-Za-z ]%', Sample collate Latin1_General_BIN ) as Part2,
      -- Put it together into a single status.
      case
      when PatIndex( '[^A-Z]%', Sample collate Latin1_General_BIN ) = 0 and
      PatIndex( '_%[^-A-Za-z ]%', Sample collate Latin1_General_BIN ) = 0 then 'Good'
      else 'Bad' end as Status
      from @Samples;


      Note that the default collation tends to be case-insensitive. Try changing the Part1 line by removing the explicit collation.






      share|improve this answer

























        up vote
        1
        down vote













        Sometimes the trick to using pattern matching is to find bad, rather than good, patterns. To validate a string of unknown length (rather than extract a substring) you can search for the patterns of unacceptable characters:



        declare @Samples as Table ( Sample VarChar(16) );
        insert into @Samples ( Sample ) values
        ( 'Worktester' ), ( 'Foo Bar' ), ( 'Voot-Plex' ),
        ( 'BR549' ), ( ' Spaced Out' ), ( 'low down' ), ( 'Oops!' );

        select Sample,
        -- Check the first character for uppercase alpha only.
        PatIndex( '[^A-Z]%', Sample collate Latin1_General_BIN ) as Part1,
        -- Check the remaining characters for any mix of alpha, space and hyphen.
        PatIndex( '_%[^-A-Za-z ]%', Sample collate Latin1_General_BIN ) as Part2,
        -- Put it together into a single status.
        case
        when PatIndex( '[^A-Z]%', Sample collate Latin1_General_BIN ) = 0 and
        PatIndex( '_%[^-A-Za-z ]%', Sample collate Latin1_General_BIN ) = 0 then 'Good'
        else 'Bad' end as Status
        from @Samples;


        Note that the default collation tends to be case-insensitive. Try changing the Part1 line by removing the explicit collation.






        share|improve this answer























          up vote
          1
          down vote










          up vote
          1
          down vote









          Sometimes the trick to using pattern matching is to find bad, rather than good, patterns. To validate a string of unknown length (rather than extract a substring) you can search for the patterns of unacceptable characters:



          declare @Samples as Table ( Sample VarChar(16) );
          insert into @Samples ( Sample ) values
          ( 'Worktester' ), ( 'Foo Bar' ), ( 'Voot-Plex' ),
          ( 'BR549' ), ( ' Spaced Out' ), ( 'low down' ), ( 'Oops!' );

          select Sample,
          -- Check the first character for uppercase alpha only.
          PatIndex( '[^A-Z]%', Sample collate Latin1_General_BIN ) as Part1,
          -- Check the remaining characters for any mix of alpha, space and hyphen.
          PatIndex( '_%[^-A-Za-z ]%', Sample collate Latin1_General_BIN ) as Part2,
          -- Put it together into a single status.
          case
          when PatIndex( '[^A-Z]%', Sample collate Latin1_General_BIN ) = 0 and
          PatIndex( '_%[^-A-Za-z ]%', Sample collate Latin1_General_BIN ) = 0 then 'Good'
          else 'Bad' end as Status
          from @Samples;


          Note that the default collation tends to be case-insensitive. Try changing the Part1 line by removing the explicit collation.






          share|improve this answer












          Sometimes the trick to using pattern matching is to find bad, rather than good, patterns. To validate a string of unknown length (rather than extract a substring) you can search for the patterns of unacceptable characters:



          declare @Samples as Table ( Sample VarChar(16) );
          insert into @Samples ( Sample ) values
          ( 'Worktester' ), ( 'Foo Bar' ), ( 'Voot-Plex' ),
          ( 'BR549' ), ( ' Spaced Out' ), ( 'low down' ), ( 'Oops!' );

          select Sample,
          -- Check the first character for uppercase alpha only.
          PatIndex( '[^A-Z]%', Sample collate Latin1_General_BIN ) as Part1,
          -- Check the remaining characters for any mix of alpha, space and hyphen.
          PatIndex( '_%[^-A-Za-z ]%', Sample collate Latin1_General_BIN ) as Part2,
          -- Put it together into a single status.
          case
          when PatIndex( '[^A-Z]%', Sample collate Latin1_General_BIN ) = 0 and
          PatIndex( '_%[^-A-Za-z ]%', Sample collate Latin1_General_BIN ) = 0 then 'Good'
          else 'Bad' end as Status
          from @Samples;


          Note that the default collation tends to be case-insensitive. Try changing the Part1 line by removing the explicit collation.







          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Nov 19 at 17:58









          HABO

          10.9k52744




          10.9k52744
























              up vote
              0
              down vote













              Could you try this one



              patindex('[A-Z]%[A-Za-z ''-]%','Worktester')





              share|improve this answer





















              • The % wildcards will accept any characters, hence it won't filter out "My bad!" for ending in a bang.
                – HABO
                Nov 19 at 18:00










              • Thank you, It works
                – user3687828
                Nov 20 at 9:22










              • @jigga: If my title is set as "M R" with space in between. when using Ltrim(Rtrim(Title)), this is not returning "MR"
                – user3687828
                Nov 20 at 11:36










              • @user3687828 so you want all the spaces to be removed? I thought you wanted the first space to be filtered out
                – jigga
                Nov 22 at 18:04















              up vote
              0
              down vote













              Could you try this one



              patindex('[A-Z]%[A-Za-z ''-]%','Worktester')





              share|improve this answer





















              • The % wildcards will accept any characters, hence it won't filter out "My bad!" for ending in a bang.
                – HABO
                Nov 19 at 18:00










              • Thank you, It works
                – user3687828
                Nov 20 at 9:22










              • @jigga: If my title is set as "M R" with space in between. when using Ltrim(Rtrim(Title)), this is not returning "MR"
                – user3687828
                Nov 20 at 11:36










              • @user3687828 so you want all the spaces to be removed? I thought you wanted the first space to be filtered out
                – jigga
                Nov 22 at 18:04













              up vote
              0
              down vote










              up vote
              0
              down vote









              Could you try this one



              patindex('[A-Z]%[A-Za-z ''-]%','Worktester')





              share|improve this answer












              Could you try this one



              patindex('[A-Z]%[A-Za-z ''-]%','Worktester')






              share|improve this answer












              share|improve this answer



              share|improve this answer










              answered Nov 19 at 17:45









              jigga

              22139




              22139












              • The % wildcards will accept any characters, hence it won't filter out "My bad!" for ending in a bang.
                – HABO
                Nov 19 at 18:00










              • Thank you, It works
                – user3687828
                Nov 20 at 9:22










              • @jigga: If my title is set as "M R" with space in between. when using Ltrim(Rtrim(Title)), this is not returning "MR"
                – user3687828
                Nov 20 at 11:36










              • @user3687828 so you want all the spaces to be removed? I thought you wanted the first space to be filtered out
                – jigga
                Nov 22 at 18:04


















              • The % wildcards will accept any characters, hence it won't filter out "My bad!" for ending in a bang.
                – HABO
                Nov 19 at 18:00










              • Thank you, It works
                – user3687828
                Nov 20 at 9:22










              • @jigga: If my title is set as "M R" with space in between. when using Ltrim(Rtrim(Title)), this is not returning "MR"
                – user3687828
                Nov 20 at 11:36










              • @user3687828 so you want all the spaces to be removed? I thought you wanted the first space to be filtered out
                – jigga
                Nov 22 at 18:04
















              The % wildcards will accept any characters, hence it won't filter out "My bad!" for ending in a bang.
              – HABO
              Nov 19 at 18:00




              The % wildcards will accept any characters, hence it won't filter out "My bad!" for ending in a bang.
              – HABO
              Nov 19 at 18:00












              Thank you, It works
              – user3687828
              Nov 20 at 9:22




              Thank you, It works
              – user3687828
              Nov 20 at 9:22












              @jigga: If my title is set as "M R" with space in between. when using Ltrim(Rtrim(Title)), this is not returning "MR"
              – user3687828
              Nov 20 at 11:36




              @jigga: If my title is set as "M R" with space in between. when using Ltrim(Rtrim(Title)), this is not returning "MR"
              – user3687828
              Nov 20 at 11:36












              @user3687828 so you want all the spaces to be removed? I thought you wanted the first space to be filtered out
              – jigga
              Nov 22 at 18:04




              @user3687828 so you want all the spaces to be removed? I thought you wanted the first space to be filtered out
              – jigga
              Nov 22 at 18:04










              up vote
              0
              down vote













              Using PATINDEX for pattern matching can be a pain.



              Since the pattern syntax for LIKE or PATINDEX is way more limited than for Regexp.



              If it's just to filter out those with other characters, you could use a LIKE instead of PATINDEX.

              Since they uses the same syntax, and you don't need to know the position for this.



              And it seems you just have to check if the first character is a letter, and if it doesn't contain anything other than letters, space, quotes or dash.



              declare @Table table (
              ID int identity(1,1) primary key,
              Col varchar(30) not null,
              IsValid bit
              );

              insert into @Table (col, isValid) values
              ('Foobar',1), ('Foo-''Bar''',1), ('foo bar',1),
              (' Foo',0), ('F0ob4r',0), ('Foo?',0);

              SELECT *
              FROM @Table
              WHERE Col LIKE '[a-z]%'
              AND Col NOT LIKE '%[^a-z ''-]%';


              Result: Those with isValid = 1



              Or use it in a CASE



              SELECT *,
              (CASE
              WHEN Col LIKE '[a-z]%' AND Col NOT LIKE '%[^a-z ''-]%'
              THEN 1
              ELSE 0
              END) AS isOk
              FROM @Table;





              share|improve this answer



























                up vote
                0
                down vote













                Using PATINDEX for pattern matching can be a pain.



                Since the pattern syntax for LIKE or PATINDEX is way more limited than for Regexp.



                If it's just to filter out those with other characters, you could use a LIKE instead of PATINDEX.

                Since they uses the same syntax, and you don't need to know the position for this.



                And it seems you just have to check if the first character is a letter, and if it doesn't contain anything other than letters, space, quotes or dash.



                declare @Table table (
                ID int identity(1,1) primary key,
                Col varchar(30) not null,
                IsValid bit
                );

                insert into @Table (col, isValid) values
                ('Foobar',1), ('Foo-''Bar''',1), ('foo bar',1),
                (' Foo',0), ('F0ob4r',0), ('Foo?',0);

                SELECT *
                FROM @Table
                WHERE Col LIKE '[a-z]%'
                AND Col NOT LIKE '%[^a-z ''-]%';


                Result: Those with isValid = 1



                Or use it in a CASE



                SELECT *,
                (CASE
                WHEN Col LIKE '[a-z]%' AND Col NOT LIKE '%[^a-z ''-]%'
                THEN 1
                ELSE 0
                END) AS isOk
                FROM @Table;





                share|improve this answer

























                  up vote
                  0
                  down vote










                  up vote
                  0
                  down vote









                  Using PATINDEX for pattern matching can be a pain.



                  Since the pattern syntax for LIKE or PATINDEX is way more limited than for Regexp.



                  If it's just to filter out those with other characters, you could use a LIKE instead of PATINDEX.

                  Since they uses the same syntax, and you don't need to know the position for this.



                  And it seems you just have to check if the first character is a letter, and if it doesn't contain anything other than letters, space, quotes or dash.



                  declare @Table table (
                  ID int identity(1,1) primary key,
                  Col varchar(30) not null,
                  IsValid bit
                  );

                  insert into @Table (col, isValid) values
                  ('Foobar',1), ('Foo-''Bar''',1), ('foo bar',1),
                  (' Foo',0), ('F0ob4r',0), ('Foo?',0);

                  SELECT *
                  FROM @Table
                  WHERE Col LIKE '[a-z]%'
                  AND Col NOT LIKE '%[^a-z ''-]%';


                  Result: Those with isValid = 1



                  Or use it in a CASE



                  SELECT *,
                  (CASE
                  WHEN Col LIKE '[a-z]%' AND Col NOT LIKE '%[^a-z ''-]%'
                  THEN 1
                  ELSE 0
                  END) AS isOk
                  FROM @Table;





                  share|improve this answer














                  Using PATINDEX for pattern matching can be a pain.



                  Since the pattern syntax for LIKE or PATINDEX is way more limited than for Regexp.



                  If it's just to filter out those with other characters, you could use a LIKE instead of PATINDEX.

                  Since they uses the same syntax, and you don't need to know the position for this.



                  And it seems you just have to check if the first character is a letter, and if it doesn't contain anything other than letters, space, quotes or dash.



                  declare @Table table (
                  ID int identity(1,1) primary key,
                  Col varchar(30) not null,
                  IsValid bit
                  );

                  insert into @Table (col, isValid) values
                  ('Foobar',1), ('Foo-''Bar''',1), ('foo bar',1),
                  (' Foo',0), ('F0ob4r',0), ('Foo?',0);

                  SELECT *
                  FROM @Table
                  WHERE Col LIKE '[a-z]%'
                  AND Col NOT LIKE '%[^a-z ''-]%';


                  Result: Those with isValid = 1



                  Or use it in a CASE



                  SELECT *,
                  (CASE
                  WHEN Col LIKE '[a-z]%' AND Col NOT LIKE '%[^a-z ''-]%'
                  THEN 1
                  ELSE 0
                  END) AS isOk
                  FROM @Table;






                  share|improve this answer














                  share|improve this answer



                  share|improve this answer








                  edited Nov 20 at 21:15

























                  answered Nov 19 at 20:10









                  LukStorms

                  11k31532




                  11k31532






























                      draft saved

                      draft discarded




















































                      Thanks for contributing an answer to Stack Overflow!


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid



                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.


                      To learn more, see our tips on writing great answers.





                      Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


                      Please pay close attention to the following guidance:


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid



                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.


                      To learn more, see our tips on writing great answers.




                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function () {
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53378762%2fpatindex-expression%23new-answer', 'question_page');
                      }
                      );

                      Post as a guest















                      Required, but never shown





















































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown

































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown







                      Popular posts from this blog

                      Wiesbaden

                      Marschland

                      Dieringhausen