简体   繁体   English

C#Regex“+”组返回空字符串

[英]C# Regex “+” group returning empty string

I'm trying to match the following strings and extract the numbers: 我正在尝试匹配以下字符串并提取数字:

"Control 1"
"Control 2"

and I want to make sure that I avoid similar strings such as: 我想确保我避免类似的字符串,例如:

"Indication 1"
"Local Control Input 2"

This is the pattern I'm using: 这是我正在使用的模式:

@"^Control (?<slot>\d+)$"

It works perfectly, and match.Groups["slot"].Value returns the number. 它完美地工作,并match.Groups["slot"].Value返回数字。 However, I discovered that I also need to be able to match the following: 但是,我发现我还需要能够匹配以下内容:

"Office In 1"
"Office In 2"

I modified my regex to this: 我修改了我的正则表达式:

@"^(?:Control)|(?:Office In) (?<slot>\d+)$"

The problem is that now, match.Groups["slot"].Value is returning an empty string! 问题是现在, match.Groups["slot"].Value返回一个空字符串! Doesn't the + require that there be at least one digit? +是否要求至少有一个数字? I randomly tried adding an extra non-capturing group around the two existing ones: 我随机尝试在现有的两个组中添加一个额外的非捕获组:

@"^(?:(?:Control)|(?:Office In)) (?<slot>\d+)$"

That fixes the problem, but I'm not sure why. 这解决了问题,但我不确定为什么。

Alternation has the highest precedence in Regular expressions. 在正则表达式中,轮换具有最高优先级。 Your original regex is "^(?:Control)" (Control at the beginning of the string) OR "(?:Office In) (?<slot>\\d+)$" (Office In #### at the end of the string). 您的原始正则表达式是"^(?:Control)" (字符串开头的控件)或"(?:Office In) (?<slot>\\d+)$" (办公室在####末尾)字符串)。

Try this regular expression: 试试这个正则表达式:

@"^(?:Control|Office In) (?<slot>\d+)$"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM