regex one dot or one underline validator

regex, validation, zend-validate

Solution

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

Problem

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

Original source