Skip to main content
 首页 » 编程设计

c#之为什么正则表达式没有按预期工作

2024年01月28日30wuhuacong

有一个字符串可以有一个或多个字符串范围。 这些是正确的字符串:

"" 
"asd-asd" 
"asd-asd;asd-asd" 
"asd-asd;asd-asd;" 
"asd-asd;asd-asd;asd0-asd1" 

但是字符串 "asd0-asd1-asd2" 应该是无效的。我写了以下正则表达式:

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

它并没有像我预期的那样工作——这个正则表达式表明这个字符串是匹配的。为什么?

请您参考如下方法:

你需要让你的正则表达式更复杂一点:

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

解释:

^               # 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