2016-09-22 46 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

我對正則表達式解析器一無所知。我同意這看起來至少表面上像一個錯誤。我發現正則表達式的文檔不如我想要的那麼精確,所以很難用正當的理由來說明正確的行爲是什麼,但這對我來說看起來不正確。 –

相關問題