我正在尝试匹配以下字符串并提取数字:
"Control 1"
"Control 2"
并且我想确保避免使用类似的字符串,例如:
"Indication 1"
"Local Control Input 2"
这是我正在使用的模式:
@"^Control (?<slot>\d+)$"
它运行完美,match.Groups["slot"].Value
返回数字。但是,我发现我还需要能够匹配以下内容:
"Office In 1"
"Office In 2"
我将正则表达式修改为:
@"^(?:Control)|(?:Office In) (?<slot>\d+)$"
问题是现在,match.Groups["slot"].Value
返回一个空字符串! +
不要求至少有一个数字吗?我随机尝试在两个现有的周围添加一个额外的非捕获组:
@"^(?:(?:Control)|(?:Office In)) (?<slot>\d+)$"
这解决了问题,但我不确定原因。
最佳答案
交替在正则表达式中具有最高的优先级。您原来的正则表达式是 "^(?:Control)"
(字符串开头的控件)或 "(?:Office In) (?<slot>\d+)$"
(Office In #### 在字符串的末尾)。
试试这个正则表达式:
@"^(?:Control|Office In) (?<slot>\d+)$"
关于C# 正则表达式 "+"组返回空字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19934499/