Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

regular expression for matching

Tags:

regex

It is for a normal register name, could be 1-n characters with a-zA-Z and -, like

larry-cai, larrycai, larry-c-cai, l,

but - can't be the first and end character, like

-larry, larry-

my thinking is like

^[a-zA-Z]+[a-zA-Z-]*[a-zA-Z]+$

but the length should be 2 if my regex

should be simple, but don't how to do it

Will be nice if you can write it and pass http://tools.netshiftmedia.com/regexlibrary/

like image 477
Larry Cai Avatar asked Apr 16 '26 05:04

Larry Cai


2 Answers

You didn't specify which regex engine you're using. One way would be (if your engine supports lookaround):

^(?!-)[A-Za-z-]+(?<!-)$

Explanation:

^           # Start of string  
(?!-)       # Assert that the first character isn't a dash
[A-Za-z-]+  # Match one or more "allowed" characters
(?<!-)      # Assert that the previous character isn't a dash...
$           # ...at the end of the string.

If lookbehind is not available (for example in JavaScript):

^(?!-)[A-Za-z-]*[A-Za-z]$

Explanation:

^           # Start of string  
(?!-)       # Assert that the first character isn't a dash
[A-Za-z-]*  # Match zero or more "allowed" characters
[A-Za-z]    # Match exactly one "allowed" character except dash
$           # End of string
like image 143
Tim Pietzcker Avatar answered Apr 18 '26 18:04

Tim Pietzcker


This should do it:

^[a-zA-Z]+(-[a-zA-Z]+)*$

With this there need to be one or more alphabetic characters at the begin (^[a-zA-Z]+). And if there is a - following, it needs to be followed by at least one alphabetic character (-[a-zA-Z]+). That pattern can be repeated arbitrary times until the end of the string is reached.

like image 30
Gumbo Avatar answered Apr 18 '26 17:04

Gumbo



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!