Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex that does not allow consecutive dots

Tags:

regex

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?

like image 829
Miguel Moura Avatar asked Nov 21 '16 11:11

Miguel Moura


People also ask

How do you escape a dot in regex?

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

What is Slash's regex?

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.

Is dot a special character in regex?

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


2 Answers

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 end
like image 199
anubhava Avatar answered Nov 04 '22 10:11

anubhava


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
like image 26
Wiktor Stribiżew Avatar answered Nov 04 '22 09:11

Wiktor Stribiżew