爲什麼對於相同的模式,類似的搜索字符串會得到不同的行爲?對於幾乎相同的輸入字符串,正則表達式會產生不同的結果
請注意以下內容由同事撰寫,而不是由我自己撰寫。
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)(?!))$
),它不使用上述條件。
'|'在哪裏?字符? – jdweng
@jdweng:鏈接的文檔將其列爲可選項,但不會說如果缺失會發生什麼。 –
試試這個:(?(。+ \ d \ b)y)(http://regexstorm.net/tester)。請注意,它與xy xya中的y都匹配。這可能與忽略|的行爲有關因爲(?(。+ \ d \ b)y |失敗)沒有給我任何匹配。 – Jacob