简体   繁体   中英

Regex match doesn't contain full match text

I'm having an issue with a Regex match not containing the full text of what it matched. It only contains the last letter of the month name, and the day and year portion. I thought it would contain the full month name, and the day and year portion, since that is what my regex expression contains, but for some reason it doesn't.

Here is my example that replicates my issue: https://ideone.com/wJPj1d

using System;
using System.Text;
using System.Text.RegularExpressions;

public class Test
{
    public static void Main()
    {
        string text = "<strong>Date of Hire: </strong>November 2, 2015<br />";
        string foundMatch = "No match found";
        Regex dateFormat = new Regex("[January|February|March|April|May|June|July|August|September|October|November|December] [0-9]{1,2}, [0-9]{4}");
        MatchCollection matches = dateFormat.Matches(text);
        if(matches.Count > 0)
        {
            foundMatch = matches[0].ToString();
        }
        Console.WriteLine(foundMatch);
    }
}

What I get for output is: r 2, 2015

What I would expect it to be: November 2, 2015

Use a group (...) , not a character class [...] :

Regex dateFormat = new Regex("(January|February|March|April|May|June|July|August|September|October|November|December) [0-9]{1,2}, [0-9]{4}");
                              ^                                                                                     ^

See this IDEONE demo

If you do not need to access the captured month name, use a non-capturing group (?:...) .

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