我正在尝试匹配以下字符串并提取数字:
"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+)$"
这解决了问题,但我不确定原因。
答案 0 :(得分:4)
轮替在正则表达式中具有最高优先级。您的原始正则表达式为"^(?:Control)"
(字符串开头的控件)或"(?:Office In) (?<slot>\d+)$"
(字符串末尾的Office#####)。
试试这个正则表达式:
@"^(?:Control|Office In) (?<slot>\d+)$"