Why does the regex work not as expected?

前端 未结 4 514
余生分开走
余生分开走 2021-01-25 14:17

There is a string which can have one or several string ranges. These are correct strings:

\"\"
\"asd-asd\"
\"asd-asd;asd-asd\"
\"asd-asd;asd-asd;\"
\"asd-asd;asd         


        
相关标签:
4条回答
  • 2021-01-25 15:01

    There's a slight add to the Answer of @Tim. This regex is not matching the "asd-asd;asd-asd;" if you're using .Net regex library. But if you add a ';' as option before string ends then it'll cover all the cases.

    ^([^;-]+-[^;-]+(;[^;-]+-[^;-]+)*);?$
    

    Now this will match all the valid strings provided except the Invalid - "asd0-asd1-asd2"

    0 讨论(0)
  • 2021-01-25 15:07

    It matches because of ;? which makes the ; optional. You are trying to test something with context, regex is not the easiest tool to do this.

    0 讨论(0)
  • You need to make your regex a little more complicated:

    ^([^;-]+-[^;-]+(;[^;-]+-[^;-]+)*)?$
    

    Explanation:

    ^               # Start of the string
    (               # Start of first group:
     [^;-]+-[^;-]+  # Match one "asd-asd"
     (              # Start of second group
      ;             # Match ;
      [^;-]+-[^;-]+ # Match another "asd-asd"
     )*             # Repeat the second group any number of times (including zero)
    )?              # Make the entire first group optional     
    $               # End of string
    
    0 讨论(0)
  • 2021-01-25 15:15

    To avoid making the semicolon optional, instead you could use (;|$).
    This will force the match of a semicolon unless you are at the end of the string.

    ^(([^;-]+-[^;-]+)(;|$))*$
    
    0 讨论(0)
提交回复
热议问题