Lemon Lemon - 3 months ago 9
Javascript Question

Regex - No repeation of period and comma and hyphen

I am trying to create a regex for addresses.

I currently have

, but it matches the repeating period, repeating hyphen, and repeating comma. Is there any way I could limit the count of comma, hyphen, and period to 1?

It should match
"5432 Lorem St. Tokyo, Japan 1234-54"

and it shouldn't match
"5323 Dolor Ave... Kyoto,,,, Japan 555-33----33"


To disallow a repeated character from the set of "comma", "dot", or "hyphen", you can use a negative lookahead anchored at the start:


The (?!.*([.,-])\1) lookahead checks if there is a repeated comma, dot or hyphen (see ([.,-])\1 - a capturing group followed with a backreference) and fails the match if found.

Also, to disallow partial matches, the anchors - ^ for start of string and $ for the end of string - are necessary.