Amir
Amir

Reputation: 11

Regex that won't allow for matches with 2 or more dots?

Right now I have a list of strings, and some of these strings have consecutive dots in them. I want to match everything except those strings with consecutive dots. For example:

fo.o.ba.r = legal --> fo..obar != legal

This is the regex I've tried using, but it doesn't seem to work how I thought it would.

(?!\.{2,})

Can anyone here put me on the right path? Thank you!

Upvotes: 1

Views: 124

Answers (2)

CertainPerformance
CertainPerformance

Reputation: 371198

From the start of the string to the end of the string, repeat any character inside a group while using negative lookahead for two dots:

^(?:(?!\.{2}).)+$

https://regex101.com/r/M5nhk7/1

Upvotes: 2

The fourth bird
The fourth bird

Reputation: 163632

You could use a negative lookahead to assert from the start of the string that what is on the right does not contain 2 dots:

^(?!.*\.{2}).+$

Regex demo

That will match:

  • ^ Assert the start of the string
  • (?! Negative lookahead
    • .* Match any character 0+ times
    • \.{2} Match 2 times a dot
  • ) Close negative lookahead
  • .+ Match any character 1+ times
  • $ Assert the end of the string

Upvotes: 0

Related Questions