Why does the regex work not as expected?

前端 未结 4 551
余生分开走
余生分开走 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:15

    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
    

提交回复
热议问题