How to conditional regex

前端 未结 4 490
无人及你
无人及你 2020-12-31 14:53

I want a regex that does one thing if it has 3 instances of .in the string, and something else if it has more than 3 instances.

for example



        
4条回答
  •  无人及你
    2020-12-31 15:48

    You can do this using the (?(?=condition)then|else) construct. However, this is not available in JavaScript (but it is available in .NET, Perl and PCRE):

    ^(?(?=(?:[^.]*\.){3}[^.]*$)aaa|eee)
    

    for example, will check if a string contains exactly three dots, and if it does, it tries to match aaa at the start of the string; otherwise it tries to match eee. So it will match the first three letters of

    aaa.bbb.ccc.ffffd
    eee.ffffd.ccc.bbb.aaa
    eee
    

    but fail on

    aaa.bbb.ccc
    eee.ffffd.ccc.bbb
    aaa.bbb.ccc.ffffd.eee
    

    Explanation:

    ^            # Start of string
    (?           # Conditional: If the following lookahead succeeds:
     (?=         #   Positive lookahead - can we match...
      (?:        #     the following group, consisting of
       [^.]*\.   #     0+ non-dots and 1 dot
      ){3}       #     3 times
      [^.]*      #     followed only by non-dots...
      $          #     until end-of-string?
     )           #   End of lookahead
     aaa         # Then try to match aaa
    |            # else...
     eee         # try to match eee
    )            # End of conditional
    

提交回复
热议问题