为什么对于相同的模式,类似的搜索字符串会得到不同的行为?对于几乎相同的输入字符串,正则表达式会产生不同的结果
请注意以下内容由同事撰写,而不是由我自己撰写。
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