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

标签 c# regex

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

""
"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

关于c# - 为什么正则表达式没有按预期工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19377322/

相关文章:

c# - C# 中是否有检查字符串是否为有效标识符的方法

c# - C# 中的泛型列表和静态变量行为

php - 如何将 eregi 转换为 preg_match?

java - 用数组中的值替换较大字符串中出现的所有子字符串

regex - NSRegularExpression 正则表达式替换希腊Unicode文本

regex - 恰好匹配 8 个数字和 0 个或多个破折号

c# - 按多列对 DataTable 进行分组并连接字符串

c# - C# 中的引用问题

c# - XAML 和 C# 代码背后的 UI 区别

正则表达式匹配字符串中的 2 个或多个数字