Pal Singh Pal Singh - 4 months ago 11
Javascript Question

Regex match character before and after underscore

I have to write a regex with matches following:


  • String should start with alphabets - [a-zA-Z]

  • String can contain alphabets, spaces, numbers,
    _
    and
    -
    (underscore and hyphen)

  • String should not end with
    _
    or
    -
    (underscore and hyphen)

  • Underscore character should not have space before and after.



I came up with the following regex, but it doesn't seems to work

/^[a-zA-Z0-9]+(\b_|_\b)[a-zA-Z0-9]+$/


Test case:

HelloWorld // Match
Hello_World //Match
Hello _World // doesn't match
Hello_ World // doesn't match
Hello _ World // doesn't match
Hello_World_1 // Match
He110_W0rld // Match
Hello - World // Match
Hello-World // Match
_HelloWorld // doesn't match

Answer

What about this?

^[a-zA-Z](\B_\B|[a-zA-Z0-9 -])*[a-zA-Z0-9 ]$

Broken down:

^               
[a-zA-Z]        allowed characters at beginning
(
 \B_\B          underscore with no word-boundary
|                 or
 [a-zA-Z0-9 -]  other allowed characters
)*
[a-zA-Z0-9 ]    allowed characters at end
$