Regex (JavaScript): match feet and/or inches

前端 未结 2 649
轻奢々
轻奢々 2021-01-22 13:13

I\'m trying to match feet and inches but I can\'t manage to get \"and/or\" so if first half is correct it validates:

Code: (in javascript)



        
相关标签:
2条回答
  • 2021-01-22 13:42

    Remove the + at the end (which allows more than one instance of feet/inches right now) and check for an empty string or illegal entries like 1'2 using a separate negative lookahead assertion. I've also changed the regex so group 1 contains the feet and group 2 contains the inches (if matched):

    ^(?!$|.*\'[^\x22]+$)(?:([0-9]+)\')?(?:([0-9]+)\x22?)?$
    

    Test it live on regex101.com.

    Explanation:

    ^          # Start of string
    (?!        # Assert that the following can't match here:
     $         # the end of string marker (excluding empty strings from match)
    |          # or
     .*\'      # any string that contains a '
     [^\x22]+  # if anything follows that doesn't include a "
     $         # until the end of the string (excluding invalid input like 1'2)
    )          # End of lookahead assertion
    (?:        # Start of non-capturing group:
     ([0-9]+)  # Match an integer, capture it in group 1
     \'        # Match a ' (mandatory)
    )?         # Make the entire group optional
    (?:        # Start of non-capturing group:
     ([0-9]+)  # Match an integer, capture it in group 2
     \x22?     # Match a " (optional)
    )?         # Make the entire group optional
    $          # End of string
    
    0 讨论(0)
  • 2021-01-22 13:44

    try this

    var pattern = "^\d+(\'?(\d+\x22)?|\x22)$";
    
    0 讨论(0)
提交回复
热议问题