c# - 在精确偏移处匹配正则表达式

标签 c# .net regex

我想检查某个模式(例如,双引号字符串)是否在确切位置匹配。

示例

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/

相关文章:

jquery - 通过 jQuery 从部分文本中删除冒号?

c# - 对使用 Azure 云服务的代码进行单元测试

c# - 您必须添加对程序集的引用…而无需web.config文件

c# - .NET 运行时 (CLR)、JIT 编译器究竟位于何处?

.net - 将SAP连接到.NET的选项

C# Regex 替换字符串末尾的圆括号和内容

c# - 在 nuget 包中包含引用的项目 DLL [.Net Core RC3 *.csproj 文件]

c# - 处理您的请求时发生错误。 MVC 4

.net - 带有 IIS SSL 证书的 OpenPOP.POP3

python - 使用正则表达式将每行的第一个字母大写