Code
using System;
using System.Text.RegularExpressions;
namespace RegexNoMatch {
class Program {
static void Main () {
string input = "a foobar& b";
string regex1 = "(foobar|foo)&?";
string regex2 = "(foo|foobar)&?";
string replace = "$1";
Console.WriteLine(Regex.Replace(input, regex1, replace));
Console.WriteLine(Regex.Replace(input, regex2, replace));
Console.ReadKey();
}
}
}
Expected output
a foobar b
a foobar b
Actual output
a foobar b
a foobar& b
Question
Why does replacing not work when the order of "foo" and "foobar" in regex pattern is changed? How to fix this?
The regular expression engine tries to match the alternatives in the order in which they are specified. So when the pattern is (foo|foobar)&?
it matches foo
immediately and continues trying to find matches. The next bit of the input string is bar& b
which cannot be matched.
In other words, because foo
is part of foobar
, there is no way (foo|foobar)
will ever match foobar
, since it will always match foo
first.
때때로 이것은 실제로 매우 유용한 트릭이 될 수 있습니다. 패턴은 (o|a|(\w))
캡처 할 수 \w
및 a
또는 o
다른 :
Regex.Replace("a foobar& b", "(o|a|(\\w))", "$2") // fbr& b
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다