简体   繁体   中英

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:

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.

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. You need to use the Groups property of the Match class to get the actual groups found.

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 ?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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