Search code examples
c#regexvalidation

String validation using regular expressions


I need to create a regex for 3 rules.

  1. The string can start with a letter or _. No numbers are allowed before the letter or _.
  2. The _ can be added in any place.
  3. Using special characters or spaces is not allowed.

I created 2 regexes(^[A-Za-z0-9_]*$ and ^[^0-9]*$) but don't know how to combine them together. Also, the rules do not include a number at the end(like _Sss12).

_Aaa12 - correct
Aaa    - correct
aa aa  - fail
12aa   - fail

Solution

  • As far as I can see, you want to match an identifier, which

    • must start from letter A..Z, a..z or _
    • can contain letters A..Z, a..z or _, or digits 0..9

    If it's your case then the pattern can be

    ^[A-Za-z_][A-Za-z0-9_]*$
    

    where

    ^             - anchor, start of the string
    [A-Za-z_]     - Letter A..Z or a..z or symbol _
    [A-Za-z0-9_]* - Zero or more letters, digits or _
    $             - anchor, end of the string
    

    If letters can be any Unicode letter, not necessary Latin ones, you can use \p{L} (for any Unicode digit, not necessary 0..9 \d can be used, but I doubt if you want Persian or Indian digits in the pattern):

    ^[\p{L}_][\p{L}0-9_]*$