. net使用不同的正则表达式引擎吗?

本文关键字:正则表达式 引擎 net | 更新日期: 2023-09-27 18:15:56

我试图从使用正则表达式捕获3个不同的字符串:

Del Mar, CA, 92014

结果应该是3个单独的捕获字符串:

  • 德尔
  • CA
  • 92014

下面regex在regexlib.com中工作,输出捕获这3个字符串。但这在c# . net中不起作用。net找到匹配,但不捕获3个不同的字符串

([a-zA-Z's]*),*'s*([a-zA-Z]{2}),*'s*([0-9]{5,10})'s*

我尝试了不同的RegexOptions (IgnoreCase, ExplicitCapture, IgnorePatternWhitespace),它们都有相同的结果(找到匹配但不捕获)。

c#代码:

var _regex = new System.Text.RegularExpressions.Regex(@"([a-zA-Z's]*),*'s*([a-zA-Z]{2}),*'s*([0-9]{5,10})'s*", RegexOptions.IgnoreCase);
var _matches = _regex.Matches("Del Mar, CA, 92014");
return _matches.Cast<Match>()
   .Select(m => m.Value)
   .ToArray();

. net使用不同的正则表达式引擎吗?

这对我来说很好,

String input = @"Del Mar, CA, 92014";
Regex rgx = new Regex(@"([a-zA-Z's]*),*'s*([a-zA-Z]{2}),*'s*([0-9]{5,10})'s*");
foreach (Match m in rgx.Matches(input))
{
Console.WriteLine(m.Groups[1].Value);
Console.WriteLine(m.Groups[2].Value);
Console.WriteLine(m.Groups[3].Value);
}

IDEONE

您的问题不在于您的正则表达式,而在于您如何解释结果。您将获得一个Match和4个Group s -第一个将是整个字符串,其他将是您捕获的子字符串。所以,你的返回语句可以像这样:

return _matches[0].Groups.Cast<Group>().Skip(1)
    .Select(g => g.Value)
    .ToArray();

原来,问题出在我自己的代码中。马克是对的。在这个特定的正则表达式中,捕获被"存储"在Match

中。

我最终编写了两个帮助程序来从正则表达式中提取值,一个用于Match,一个来自Group

public static IEnumerable<string> GetMatches(string input, string regexPattern)
{
    var _regex = new System.Text.RegularExpressions.Regex(regexPattern, RegexOptions.IgnoreCase);
    var _matches = _regex.Matches(input);
    return _matches.Cast<Match>()
        .Select(m => m.Value)
        .ToArray();
}
public static IEnumerable<string> GetGroups(string input, string regexPattern)
{
    var _regex = new System.Text.RegularExpressions.Regex(regexPattern, RegexOptions.IgnoreCase);
    var _matches = _regex.Matches(input);
    return (from Match _m in _matches
            from Group _g in _m.Groups
            where _g.Value != _m.Value
            select _g.Value)
        .ToArray();
}

用法:

Match:

public static IEnumerable<string> GetUSPhone(string input)
{
    return GetMatches(input, @"([0-9]( |-)?)?('(?[0-9]{3}')?|[0-9]{3})( |-)?([0-9]{3}( |-)?[0-9]{4}|[a-zA-Z0-9]{7})");
}

Group:

public static IEnumerable<string> GetUSCityStateZip(string input)
{
    return GetGroups(input, @"(?<City>[a-zA-Z'x20]*)[,]*'t*'x20*(?<State>[a-zA-Z]{2})'x2C*'t*'s*(?<ZipCode>[0-9'x2D'x20]{5,10}|'x20*)");
}