【发布时间】:2011-02-13 10:49:44
【问题描述】:
我想检查某个模式(例如双引号字符串)是否在确切位置匹配。
示例
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) 将永远不会匹配任何东西。
有什么建议吗?
编辑:
我有一个可行的解决方案(workaround)。所以我的问题都是关于速度和一个好的实现。
【问题讨论】: