简体   繁体   English

正则表达式匹配不包含完整匹配文本

[英]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 这是我复制我的问题的例子: 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 我得到的输出是: r 2, 2015

What I would expect it to be: November 2, 2015 我期望它是什么: 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 请参阅此IDEONE演示

If you do not need to access the captured month name, use a non-capturing group (?:...) . 如果您不需要访问捕获的月份名称,请使用非捕获组(?:...)

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

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