简体   繁体   English

C#-正则表达式不起作用(匹配不保留字符串)

[英]c# - regex don't work (match does not preserve the string)

Regex regOrg = new Regex(@"org(?:aniser)?\s+(\d\d):(\d\d)\s?(\d\d)?\.?(\d\d)?", RegexOptions.IgnoreCase);
MatchCollection mcOrg = regOrg.Matches(str);
Match mvOrg = regOrg.Match(str);

dayOrg = mvOrg.Value[4].ToString();
monthOrg = mvOrg.Value[5].ToString();
hourOrg = mvOrg.Value[2].ToString();
minuteOrg = mvOrg.Value[3].ToString();

This regular expression analyzes the string with text 此正则表达式使用文本分析字符串

"organiser 23:59" / "organiser 25:59 31.12" 

or 要么

"org 23:59" / "org 23:59 31.12"

Day and month of optional parameters Accordingly, I want to see the output variables dayOrg, monthOrg, hourOrg, minuteOrg with this data, but I get this: 可选参数的日期和月份相应地,我希望使用此数据查看输出变量dayOrg,monthOrg,hourOrg,minuteOrg,但是我得到了:

Query: org 23:59 31.12
The value mcOrg.Count: 1
The value dayOrg: 2
The value monthOrg: 3
The value hourOrg: g
The value minuteOrg: empty

What am I doing wrong? 我究竟做错了什么? Tried a lot of options, but it's not working. 尝试了很多选择,但不起作用。

You're not accessing the groups correctly (you're accessing individual characters of the matched string). 您没有正确访问组(正在访问匹配字符串的单个字符)。

dayOrg = mvOrg.Groups[4].Value;
monthOrg = mvOrg.Groups[5].Value;
hourOrg = mvOrg.Groups[2].Value;
minuteOrg = mvOrg.Groups[3].Value;

The reason you are getting that result is because you are getting Value[index] from the mvOrg Match. 得到该结果的原因是因为您从mvOrg Match中获得了Value [index]。

The Match class, as described on MSDN says that Value is the first match, hence you are accessing the character array of the first match instead of the groups. MSDN上所述,Match类说Value是第一个匹配项,因此您要访问第一个匹配项的字符数组而不是组。 You need to use the Groups property of the Match class to get the actual groups found. 您需要使用Match类的Groups属性来获取实际的组。

Be sure to check the count of this collection before trying to access the optional parameters. 在尝试访问可选参数之前,请确保检查此集合的计数。

I added name for you pattern so now it look like this : 我为您的模式添加了名称,因此现在看起来像这样:

            Regex regOrg = new Regex(@"org(?:aniser)?\s+(?<hourOrg>\d{2}):(?<minuteOrg>\d{2})\s?(?<dayOrg>\d{2})?\.?(?<monthOrg>\d{2})?", RegexOptions.IgnoreCase);

and you can access the result like this 您可以像这样访问结果

        Console.WriteLine(mvOrg.Groups["hourOrg"]);
        Console.WriteLine(mvOrg.Groups["minuteOrg"]);
        Console.WriteLine(mvOrg.Groups["dayOrg"]);
        Console.WriteLine(mvOrg.Groups["monthOrg"]);

Using hard coded indexes is not good practice, since you can change the regex and now need to change all the indexes ... 使用硬编码索引不是一个好习惯,因为您可以更改正则表达式,现在需要更改所有索引...
Is it what you wanted ? 是你想要的吗?

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

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