Match specific length x or y

后端 未结 3 1388
Happy的楠姐
Happy的楠姐 2020-12-08 04:59

I\'d like a regex that is either X or Y characters long. For example, match a string that is either 8 or 11 characters long. I have currently implemented this like

相关标签:
3条回答
  • 2020-12-08 05:25

    For those of us looking to capture different lengths of the same multiple try this.

    ^(?:[0-9]{32})+$

    Where 32 is the multiple you want to capture all lengths for (32, 64, 96, ...).

    0 讨论(0)
  • 2020-12-08 05:29

    With Perl, you could do:

    my $re = qr/here_is_your_regex_part/;
    my $full_regex = qr/$re{8}(?:$re{3})?$/
    
    0 讨论(0)
  • 2020-12-08 05:33

    There is one way:

    ^(?=[0-9]*$)(?:.{8}|.{11})$
    

    or alternatively, if you want to do the length check first,

    ^(?=(?:.{8}|.{11})$)[0-9]*$
    

    That way, you have the complicated part only once and a generic . for the length check.

    Explanation:

    ^       # Start of string
    (?=     # Assert that the following regex can be matched here:
     [0-9]* # any number of digits (and nothing but digits)
     $      # until end of string
    )       # (End of lookahead)
    (?:     # Match either
     .{8}   # 8 characters
    |       # or
     .{11}  # 11 characters
    )       # (End of alternation)
    $       # End of string
    
    0 讨论(0)
提交回复
热议问题