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?
(dot) metacharacter, and can match any single character (letter, digit, whitespace, everything). You may notice that this actually overrides the matching of the period character, so in order to specifically match a period, you need to escape the dot by using a slash \.
The backslash in combination with a literal character can create a regex token with a special meaning. E.g. \d is a shorthand that matches a single digit from 0 to 9. Escaping a single metacharacter with a backslash works in all regular expression flavors.
Special characters such as the dot character often need to be escaped in a regex pattern if you want to match them. For example, to match the actual dot '.
You can use it like this with additional lookaheads:
^(?!\.)(?!.*\.$)(?!.*?\.\.)[a-zA-Z0-9_.]+$
(?!\.)
- don't allow .
at start(?!.*?\.\.)
- don't allow 2 consecutive dots (?!.*\.$)
- don't allow .
at endRe-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 stringIf you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With