Regexp one symbol exactly once through the whole string

Viewed 47

Already have a working regexp ^[a-zA-Z0-9 ]{1,11}$ but recently got an update in validation: there should be all old validations and new one symbol _ which should appear in whole string exactly once.

Strings must only match:

_name
name_
name_name

validation should fail for:

_name_
__name
etc.

tried a few approaches ^[a-zA-Z0-9_ ]{1,11}$ all characters may be _

^(?)[a-zA-Z0-9 ]{1,11}(?)$ validates

alpha_
_alpha
_alpha_ (shouldn't be valid)

but not this one:

 alpha_name
2 Answers

You need to use

^(?=.{1,11}$)[a-zA-Z0-9 ]*(?:_[a-zA-Z0-9 ]*)?$

See the regex demo. Details:

  • ^ - start of string
  • (?=.{1,11}$) - a positive lookahead that requires one to eleven chars other than line break chars till end of string
  • [a-zA-Z0-9 ]* - zero or more letters, digits or spaces
  • (?:_[a-zA-Z0-9 ]*)? - an optional occurrence of _ and zero or more letters, digits or spaces
  • $ - end of string.
Related