Home > Back-end >  Regex Expression for not accepting a single underscore but accepts single alphabet
Regex Expression for not accepting a single underscore but accepts single alphabet

Time:09-29

The expression should not accept any special characters except an underscore and no numbers in it and it should accept single or more alphabets.
Examples

abc_dc (Should be accepted)

_bsc (Should be accepted)

A (Should be accepted)

_ (Should not be accepted)

a__b (should not be accepted)

I have tried:

(^(?!.*?[_]{2})[^_][a-zA-Z_] $)

but this does not accept single alphabet.

CodePudding user response:

You could try following pattern:

^(?=.*[a-zA-Z])(?=[a-zA-Z_] $)(?!.*_{2,}). 

Pattern explanation:

Generally, multiple validations are being achieved by placing lookaheads at beginning of a pattern, I used the same strategy.

Explanation:

^ - anchor - match beginning of a string

(?=.*[a-zA-Z]) - positive lookahead - assert that what follows current position is zero or more any characters (.*) followed by alphabet character. Simply - assert that what follows contains at least one letter.

(?=[a-zA-Z_] $) - assert what follows contains only letters or underscore until end of string (thanks to $).

(?!.*_{2,}) - negative lookahead - assert what follows DOES NOT contain two (or more) following underscores (thanks to _{2,}

. - match on or more of any characters.

Regex demo

CodePudding user response:

I got it.

(^(?!.*?[_]{2})[_]*[a-zA-Z] [a-zA-Z_]*$)

This should work.

CodePudding user response:

I think you could use:

^_?(?:[a-zA-Z] _?) $

See an online demo


  • ^ - Start line anchor.
  • _? - An optional hyphen.
  • (?: - Open non-capture group:
    • [a-zA-Z] _? -Match 1 alphachars and an optional hyphen.
    • )* - Close non-capture group and match 1 times.
  • $ - End line anchor.

Note: This would also allow for trailing hyphens, e.g: '_a_', 'a_' and '_a_b_'. If you don't want to allow a trailing hyphen, try ^(?:_?[a-zA-Z] ) $ instead.

  • Related