'Regex that does not allow consecutive dots
I have a Regex to allow alphanumeric, underscore and dots but not consecutive dots:
^(?!.*?[.]{2})[a-zA-Z0-9_.]+$
I also need to now allow dots in the first and last character of the string.
How can I do this?
Solution 1:[1]
Re-write the regex as
^[a-zA-Z0-9_]+(?:\.[a-zA-Z0-9_]+)*$
or (in case your regex flavor is ECMAScript compliant where \w = [a-zA-Z0-9_]):
^\w+(?:\.\w+)*$
See the regex demo
Details:
^- start of string[a-zA-Z0-9_]+- 1 or more word chars(?:\.[a-zA-Z0-9_]+)*- zero or more sequences of:\.- a dot[a-zA-Z0-9_]+- 1 or more word chars
$- end of string
Solution 2:[2]
You can try this:
^(?!.*\.\.)[A-Za-z0-9_.]+$
This will not allow any consecutive dots in the string and will also allow dot as first and last character
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Wiktor Stribiżew |
| Solution 2 | Mustofa Rizwan |
