regex one dot or one underline validator

9.3k Views Asked by At

this is my regex

^(([a-z0-9]+)\.([a-z0-9]+)){4,20}$|^(([a-z0-9]+)\_([a-z0-9]+)){4,20}$

it's gonna be a word with a single dot OR a single underline OR no uderline and dot. i also want this expression between 4 and 20 chars (it's gonna be a username in db)

this regex

^(([a-z0-9]+)\.([a-z0-9]+))$

and this one

^(([a-z0-9]+)\_([a-z0-9]+))$

works successfully but i dont know how to limit the string length

:( help please

im gonna be using it with zend framework regex validator ...

2

There are 2 best solutions below

5
On BEST ANSWER
^(?=[^\._]+[\._]?[^\._]+$)[\w\.]{4,20}$

Explanation:

^            - Start of string
(?=          - Followed by (not part of match)
  [^\._]+    - Anything but . and _
  [\._]?     - Optional . or _
  $          - End of string
)
[\w\.]{4,20} - 4-20 letters, digits, _ and .
$            - End of string

The (?=[^\._]+[\._]?[^\._]+$) ensures that the string contains no more than 1 . or _. The rest matches the string.

2
On

You should validate the length with a second validator, rather than in the regular expression, as this will improve the readability of your code. Use ^[a-z0-9]+[._][a-z0-9]+$ as your regular expression with the Regex validator, and use the StringLength validator to check the length.