Pal Singh Pal Singh - 1 year ago 94
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,
    (underscore and hyphen)

  • String should not end with
    (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


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 Source

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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download