4

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 ...

shampoo
  • 1,173
  • 12
  • 22

2 Answers2

8
^(?=[^\._]+[\._]?[^\._]+$)[\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.

Kendall Frey
  • 43,130
  • 20
  • 110
  • 148
2

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.

Mike Pelley
  • 2,939
  • 22
  • 23
  • it can be like this and its almost over :D `^[a-z0-9]+([._]{0,1})[a-z0-9]+$` – shampoo May 18 '12 at 06:50
  • Just an FYI - this is a shorter version of that regex: `^[a-z0-9]+[._]?[a-z0-9]+$` (the ? is equivalent to {0,1} and parentheses are not required). – Mike Pelley May 23 '12 at 21:29