andridomace
andridomace

Reputation: 53

Regex Expression for not accepting a single underscore but accepts single alphabet

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.

Upvotes: 2

Views: 463

Answers (3)

JvdV
JvdV

Reputation: 75870

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.

Upvotes: 2

andridomace
andridomace

Reputation: 53

I got it.

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

This should work.

Upvotes: 2

Michał Turczyn
Michał Turczyn

Reputation: 37377

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

Upvotes: 2

Related Questions