2016-09-22 35 views
0

为什么对于相同的模式,类似的搜索字符串会得到不同的行为?对于几乎相同的输入字符串,正则表达式会产生不同的结果

请注意以下内容由同事撰写,而不是由我自己撰写。

https://dotnetfiddle.net/veyasw

using System; 
using System.Text.RegularExpressions; 

public class Program 
{ 

    static void MatchTest(string input, string pattern) 
    { 
     Console.WriteLine("pattern: " + pattern); 
     Console.WriteLine("input: " + input + Environment.NewLine); 
     Match match = Regex.Match(input, pattern); 

     if (match.Success) 
      Console.WriteLine("Match '{0}' at index {1}", match.Value, match.Index); 
     else 
      Console.WriteLine("Not match"); 

     Console.WriteLine("\r\n------\r\n"); 

    } 

    static void DiffBehaviousTest() // (?(expression)yes) has different behavious. Sometime it matches with string empty. 
    { 
     /* if last character in word is digit 
       match ab 
     */ 
     string pattern = @"(?(.*\d\b)ab)"; 

     MatchTest("xy xya", pattern); 
     MatchTest("xy xyz", pattern); 
    } 


    public static void Main() 
    { 
     DiffBehaviousTest(); 
    } 
} 

其产生:

pattern: (?(.*\d\b)ab) 
input: xy xya 

Match '' at index 5 

------ 

pattern: (?(.*\d\b)ab) 
input: xy xyz 

Not match 

------ 

背景读取: 下面是a conditional regex(?(expression)yes|no)一个例子 - 如果它匹配表达式,它查找yes图案,否则它将查找没有图案。但是,我们不提供no案例模式。

这里是an example of a regex(搜索:(?(Open)(?!))$),它不使用上述条件。

+0

'|'在哪里?字符? – jdweng

+1

@jdweng:链接的文档将其列为可选项,但不会说如果缺失会发生什么。 –

+0

试试这个:(?(。+ \ d \ b)y)(http://regexstorm.net/tester)。请注意,它与xy xya中的y都匹配。这可能与忽略|的行为有关因为(?(。+ \ d \ b)y |失败)没有给我任何匹配。 – Jacob

回答

2

附录A:

string pattern = @"(?(.*\d\b)agarbage)"; 

    MatchTest("xy xya", pattern); 
    MatchTest("xy xyb", pattern); 

图案:(?。(* \ d \ b)中agarbage) 输入:XY XYA

匹配 '' 中的索引5


(?(。* \ d \ b)琼脂)

输入:xy xyb

不匹配


图表B:

string pattern = @"(?(.*\d\b)bgarbage)"; 

    MatchTest("xy xya", pattern); 
    MatchTest("xy xyb", pattern); 

图案: 输入((* \ d \ b)中bgarbage?):XY XYA

不匹配


图案: 输入((* \ d \ b)中bgarbage?):XY XYB

匹配 '' 中的索引5


它的行为像,而不|,它匹配“是”的第一个字符是“是”。

有了这个,我们得到不符合/不符合:

string pattern = @"(?(.*\d)agarbage|bgarbage)"; 

    MatchTest("xy xya", pattern); 
    MatchTest("xy xyb", pattern); 

而与此,我们得到比赛 'B' 中的索引5:

string pattern = @"(?(.*\d)a|b)"; 

    MatchTest("xy xya", pattern); 
    MatchTest("xy xyb", pattern); 

我(欲言又止)认为有可能在没有管道的情况下解析器中出现错误。但@EricLippert在这里,我对他的看法比对我自己更感兴趣。

+1

我发现相同并且同意。 –

+2

我对正则表达式解析器一无所知。我同意这看起来至少表面上像一个错误。我发现正则表达式的文档不如我想要的那么精确,所以很难用正当的理由来说明正确的行为是什么,但这对我来说看起来不正确。 –

相关问题