Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular Expression for a single occurrence within a String

Tags:

regex

I am new to Regular Expression and can't seem to do the proper syntax for what I need to do. I need regular expression for an alphanumeric string that can be 1-8 characters long and can contain at most 1 dash, but can't be a single dash alone.

Valid:

A-
-A
1234-678
ABC76-

Invalid:

-
F-1-
ABCD1234-
---   

Thanks in advance!

like image 717
user3006614 Avatar asked Mar 05 '26 23:03

user3006614


1 Answers

One way. (Sorry if this is already posted)

 #  ^(?=[a-zA-Z0-9-]{1,8}$)(?=[^-]*-?[^-]*$)(?!-$).*$

 ^                              # BOL
 (?= [a-zA-Z0-9-]{1,8} $ )      # 1 - 8 alpha-num or dash
 (?= [^-]* -? [^-]* $ )         # at most 1 dash
 (?! - $ )                      # not just a dash
 .* $

Edit: Just extend it for segments separated by comma's

 #  ^(?!,)(?:(?=(?:^|,)[a-zA-Z0-9-]{1,8}(?:$|,))(?=(?:^|,)[^-]*-?[^-]*(?:$|,))(?!(?:^|,)-(?:$|,)),?[^,]*)+(?<!,)$


 ^                         # BOL
 (?! , )                   # does not start with comma
 (?:                       # Grouping
      (?=
           (?: ^ | , )
           [a-zA-Z0-9-]{1,8}         # 1 - 8 alpha-num or dash
           (?: $ | , )
      )
      (?=
           (?: ^ | , )
           [^-]* -? [^-]*            # at most 1 dash
           (?: $ | , )
      )
      (?!
           (?: ^ | , )
           -                         # not just a dash
           (?: $ | , )
      )
      ,? [^,]*                  # consume the segment
 )+                        # Grouping, do many times

 (?<! , )                  # does not end with comma
 $                         # EOL

Edit2: If your engine doesn't support lookbehinds, this is same thing but without

 #  ^(?!,)(?:(?=(?:^|,)[a-zA-Z0-9-]{1,8}(?:$|,))(?=(?:^|,)[^-]*-?[^-]*(?:$|,))(?!(?:^|,)-(?:$|,))(?!,$),?[^,]*)+$


 ^                         # BOL
 (?! , )                   # does not start with comma
 (?:                       # Grouping
      (?=
           (?: ^ | , )
           [a-zA-Z0-9-]{1,8}         # 1 - 8 alpha-num or dash
           (?: $ | , )
      )
      (?=
           (?: ^ | , )
           [^-]* -? [^-]*            # at most 1 dash
           (?: $ | , )
      )
      (?!
           (?: ^ | , )
           -                         # not just a dash
           (?: $ | , )
      )
      (?! , $ )                 # does not end with comma

      ,? [^,]*                  # consume the segment
 )+                        # End Grouping, do many times

 $                         # EOL

Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!