Lemon Lemon - 5 months ago 12
Javascript Question

Regex - No repeation of period and comma and hyphen

I am trying to create a regex for addresses.

I currently have

[a-zA-Z0-9-\\.\-\,\\-\s\n]
, 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"

Answer

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

/^(?!.*([.,-])\1)[a-zA-Z0-9\s.,-]+$/.test(str)
  ^^^^^^^^^^^^^^^

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.