我想检查某个模式(例如,双引号字符串)是否在确切位置匹配。
示例
string text = "aaabbb";
Regex regex = new Regex("b+");
// Now match regex at exactly char 3 (offset) of text
我想检查 regex
是否正好匹配第 3 个字符。
我查看了 Regex.Match Method (String, Int32)
但它的行为并不像我预期的那样。
所以我做了一些测试和一些解决方法:
public void RegexTest2()
{
Match m;
string text = "aaabbb";
int offset = 3;
m = new Regex("^a+").Match(text, 0); // lets do a sanity check first
Assert.AreEqual(true, m.Success);
Assert.AreEqual("aaa", m.Value); // works as expected
m = new Regex("^b+").Match(text, offset);
Assert.AreEqual(false, m.Success); // this is quite strange...
m = new Regex("^.{"+offset+"}(b+)").Match(text); // works, but is not very 'nice'
Assert.AreEqual(true, m.Success);
Assert.AreEqual("bbb", m.Groups[1].Value);
m = new Regex("^b+").Match(text.Substring(offset)); // works too, but
Assert.AreEqual(true, m.Success);
Assert.AreEqual("bbb", m.Value);
}
事实上,我开始相信 new Regex("^.", 1).Match(myString)
永远不会匹配任何东西。
有什么建议吗?
编辑:
我得到了一个可行的解决方案(解决方法)。所以我的问题是关于速度和良好的实现。
最佳答案
你有没有试过docs说?
If you want to restrict a match so that it begins at a particular character position in the string and the regular expression engine does not scan the remainder of the string for a match, anchor the regular expression with a \G (at the left for a left-to-right pattern, or at the right for a right-to-left pattern). This restricts the match so it must start exactly at startat.
即将 ^
替换为 \G
:
m = new Regex(@"\\Gb+").Match(text, offset);
Assert.AreEqual(true, m.Success); // should now work
关于c# - 在精确偏移处匹配正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4983703/