为什么C#和Perl的正则表达式结果不同?

pro*_*ogr 2 c# regex perl

在C#代码之后,我重新创建了C#的perl代码.它是相同的正则表达式,但其结果是不同的.Perl代码被捕获为"a"但C#代码被捕获为"apple".是什么让它与众不同?

C#代码

string word = Regex.Replace("apple", "(?<C>a(?=pple)|b(?=anana)|c(?=herry))", "${C}");

Console.WriteLine("fruit\'s initial: {0}", word); // result: "fruit's initial: apple"
Run Code Online (Sandbox Code Playgroud)

Perl代码

my $word = 'apple';

if ($word =~ /(?<C>a(?=pple)|b(?=anana)|c(?=herry))/) {
print "fruit\'s initial: $+{C}"; // result: "fruit's initial: a"
}
Run Code Online (Sandbox Code Playgroud)

Wik*_*żew 8

在Perl中,您匹配并捕获第一个,a然后pple进入组"C",然后打印它.在C#中,您替换a后跟with pple,结果a没有apple变化.

改为使用匹配:

var m = Regex.Match("apple", "(?<C>a(?=pple)|b(?=anana)|c(?=herry))");
if (m.Success)
{
    Console.WriteLine("fruit\'s initial: {0}", m.Groups["C"].Value);
}
Run Code Online (Sandbox Code Playgroud)

请参阅C#演示.

这里,正则表达式匹配分配给m变量.如果匹配发生(if (m.Success)),您可以使用组"C"值m.Groups["C"].Value.