Kian Cross
Kian Cross

Reputation: 1818

Regular expression to match dot which has letter after it, before next dot or end of line

I want a regular expression which will match a dot . which has a letter after it at some point before the next dot . or end of line.

For example the following would be valid: .foo.bar.

.foo.123 would be invalid because it contains .123 which has no letters after the dot.

So far I've got:

^([a-z0-9)]|\.(?=.*[a-z].*\.))+$

I understand that the problem with the above is the final match for a . in the positive lookahead: it will always fail to match. I think something like "if dot exists match, else match end of line". If I use ($|\.) in place of the final match this still doesn't work, I assume because it tries both even when a . is matched.

I'd like to avoid using look-behinds. I want match the whole string, not just the dots.

Upvotes: 0

Views: 3194

Answers (1)

Alex Collins
Alex Collins

Reputation: 570

This regex possibly with some small changes should work. ^(?:\.[^\.\s]*[a-zA-Z][^\.\s]*)+$

Regex101 demo.

Breakdown of how it works:

  • ^ - Start of new line
  • (?:\.[^\.\s]*[a-zA-Z][^\.\s]*) - Grab period followed by all text before the next period or new line. Ensure there is at least one letter.
    • \. - Start with period.
    • [^\.\s]* - Anything but a space or . any number of times.
    • [a-zA-Z] - Ensure at least one letter per period.
    • [^\.\s]* - Anything but a space or . any number of times.
  • + - Once or more
  • $ - End of line

Upvotes: 1

Related Questions