Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex: Any word and numeric combination but with a single underscore

Tags:

regex

I would like to match a whole string if it contains letters or numbers or a single underscore sequence, so:

Accepted:

  • H_i_there
  • _this_is_OK_
  • _x_y_5_z
  • abddd_cdxxx

Not accepted:

  • s___2
  • __s__t__2
  • __x____x4

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.

like image 774
The Quantum Physicist Avatar asked Oct 16 '25 14:10

The Quantum Physicist


1 Answers

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 string

A less efficient, but shorter pattern:

^(?:_?[a-zA-Z0-9]+)*_?$

See this demo.

like image 69
Wiktor Stribiżew Avatar answered Oct 18 '25 08:10

Wiktor Stribiżew



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!