sean sean - 1 month ago 9
C# Question

How to get exact regex for accepting Number with alphabet only?

Hi I tried to get the exact regex for matching Number with alphabet only,
I tried this

Regex.IsMatch("1111", @"^[a-zA-Z0-9]+$")


but the output is true.

Here is what I want output

12345678 -> False
abcdefgh -> False
ABCDEFGH -> False
1234abcd -> True
1234ABCD -> True

Answer

Try the following positive lookahead matching expression:

^(?=.*[a-zA-Z])(?=.*[0-9])[a-zA-Z0-9]+$

This asserts that both grouped expressions are true and returns the full string on match.

Example: https://regex101.com/r/GxPPt9/2

Comments