Regex non-consecutive chars

后端 未结 4 1180
别那么骄傲
别那么骄傲 2021-01-06 17:32

Currently I have:

[A-Za-z0-9._%+-]

This matches any string that contains letters, numbers, and certain special chars (._%+-)

4条回答
  •  时光取名叫无心
    2021-01-06 17:44

    ^(?:[0-9A-Za-z]+|([._%+-])(?!\1))+$
    

    Broken down:

    • (?:)+ — one or more of either:
      • [0-9A-Za-z]+ — one or more alphanumeric characters or
      • ([._%+-]) — any allowed non-alphanumeric
        • (?!\1) — which isn't followed by the exact same character

    Allows:

    • foo
    • foo.+bar
    • -700.bar+baz

    Disallows:

    • foo..bar
    • foo.+bar--baz

    It works by capturing the matched non-alphanumeric characters into the first backreference (\1) each time the outer, not capturing group is matched and using a negative look-ahead ((?!)) to make sure the same character doesn't appear twice in a row. Be aware that not all regex flavors support negative look-ahead!

提交回复
热议问题