I would like to match a whole string if it contains letters or numbers or a single underscore sequence, so:
Accepted:
Not accepted:
So multiple, consecutive underscores are not allowed. How does the regex expression look for this? My version is: ^[a-zA-Z0-9]+\_{0,1}[a-zA-Z0-9]+\_{0,1}$, but this must be recursive, somehow, for it to work, and AFAIK, regex does not support such complicated functionality.
You may use
^_?[a-zA-Z0-9]+(?:_[a-zA-Z0-9]+)*_?$
See the regex demo
Details:
^ - start of string_? - an optional _[a-zA-Z0-9]+ - 1+ alphanumeric chars(?:_[a-zA-Z0-9]+)* - 0+ sequences of:
_ - 1 underscore[a-zA-Z0-9]+ - 1+ alphanumeric chars_? - an optional _$ - end of stringA less efficient, but shorter pattern:
^(?:_?[a-zA-Z0-9]+)*_?$
See this demo.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With