Regex non-consecutive chars

后端 未结 4 1190
别那么骄傲
别那么骄傲 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:41

    Using PHP's PCRE, you can do this:

    /^([A-Za-z0-9]|([._%+-])(?!\2))*$/
    

    The \2 is the back-reference that's required to detect a duplicate usage of the same symbol. I'm not sure it's possible to do this without a forward assertion and a back-reference, so there is my working regex tested against:

    'foo'         => true,
    'bar.baz'     => true,
    'bar.biz.buz' => true,
    'bar.+bar'    => true,
    'bar..bar'    => false,
    'biz.baz..'   => false,
    '..++..'      => false,
    '.faf.'       => true,
    

提交回复
热议问题