Miguel Moura
Miguel Moura

Reputation: 39364

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?

Upvotes: 14

Views: 22005

Answers (3)

anubhava
anubhava

Reputation: 785058

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

Upvotes: 36

Mustofa Rizwan
Mustofa Rizwan

Reputation: 10466

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

Tried here

Upvotes: 0

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626747

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

Upvotes: 3

Related Questions