Regex matching if maximum two occurrences of dot and dash

后端 未结 3 1907
小鲜肉
小鲜肉 2021-01-13 05:28

I need a regular expression that will match any string containing at most 2 dashes and 2 dots. There does not HAVE to be a dash nor a dot, but if there is 3+ dashes or

相关标签:
3条回答
  • 2021-01-13 05:47

    This tested regex will do the trick:

    $re = '/# Match string with 2 or fewer dots or dashes
        ^                            # Anchor to start of string.
        (?=[^.]*(?:\.[^.]*){0,2}$)   # Assert 2 or fewer dots.
        (?=[^\-]*(?:-[^\-]*){0,2}$)  # Assert 2 or fewer dashes.
        .*                           # Ok to match string.
        $                            # Anchor to end of string.
        /sx';
    
    0 讨论(0)
  • 2021-01-13 05:59

    Is this matching your expectations?

    (?!^.*?([.-]).*\1.*\1.*$)^.*$
    

    See it here on Regexr

    (?!^.*?([.-]).*\1.*\1.*$) is a negative lookahead. It matches the first .- put it in the capture group 1, and then checks if there are two more of them using hte backreference \1. As soon as it found three, the expression will not match anymore.

    ^.*$ matches everything from start to the end, if the negative lookahead has not matched.

    0 讨论(0)
  • 2021-01-13 06:09

    Use this: (?!^.*?([-.])(?:.*\1){2}.*$)^.*$

    0 讨论(0)
提交回复
热议问题