c# - .NET 正则表达式匹配方法中一致的字符串开头 anchor 行为

标签 c# .net regex

.NET 中的正则表达式(我使用的是 4.5.2)似乎具有三种(非静态)匹配方法:

  1. regex.Match(string input)搜索 input 中的第一个匹配项。
  2. regex.Match(string input, int startIndex)搜索 input 中从 startIndex 开始的第一个匹配项。
  3. regex.Match(string input, int startIndex, int length)startIndexlength 定义的 input 范围内搜索第一个匹配项。

如果我写

System.Text.RegularExpressions.Regex regex =
    new System.Text.RegularExpressions.Regex("^abc");
string str = "abc abc";

System.Text.RegularExpressions.Match match = regex.Match(str);
System.Diagnostics.Debug.WriteLine(match.Success);

然后我看到 match.SuccessTrue,正如预期的那样。 regex 匹配 str 开头的 abc

如果我再写

int index = 4;
match = regex.Match(str, index);
System.Diagnostics.Debug.WriteLine(match.Success);

从索引 4 搜索到 str 的末尾,然后我看到 match.SuccessFalse,正如预期的那样。 str 的索引 4 处有一个 abc,但索引 4 不是字符串的开头。

但是,如果我写

match = regex.Match(str, index, str.Length - index);
System.Diagnostics.Debug.WriteLine(match.Success);
System.Diagnostics.Debug.WriteLine(match.Index);

再次从索引 4 搜索到 str 的末尾,然后我看到 match.Success 出乎意料地是 True,并且 match.Index 是 4。我希望得到与调用 regex.Match(str, index) 相同的结果。

有没有办法在 .NET 正则表达式匹配方法中获得一致的字符串开头 anchor 行为?

最佳答案

来自 Regex.cs source code 中的评论,我看到 public Match Match(String input, int startat) 找到第一个匹配项,从指定位置开始public Match Match(String input, int beginning, int length) 找到第一个匹配项,将搜索限制在字符数组的指定区间内

结合您的测试结果(和 mine ),很明显 Regex.Match 方法的最后一个重载将子字符串作为一个新的单独字符串传递给正则表达式引擎。将 ^ 更改为 \A 不会有帮助。

因此,要知道匹配是否在真正的开始,你应该在自己的代码中添加逻辑,比如,如果 index 大于 0,则所有匹配都不是在真正的开始字符串的真正开始。但是,返回的索引是正确的,因此对我来说这看起来像是一个错误

关于c# - .NET 正则表达式匹配方法中一致的字符串开头 anchor 行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34643564/

相关文章:

c# - 一旦被调用者超出范围 : safe practice?,.NET 事件回调

regex - 当传递正则表达式模式的文件时,Egrep 命令挂起

c# - Unity Player 抛出异常 : System. ArgumentException:找不到 'hideFlags' 的 Get 方法

c# - 如何检查窗口是否已经打开?重复窗口

c# - 检测到包将 : Microsoft. NETCore.App 从 2.1.3 降级到 2.1.0

regex - Shell 正则表达式到行尾

regex - 匹配语法问题

c# - 将数字字符串转换为数字数组 C#?

c# - 你能捕捉到 RaceOnRCWCleanup 异常吗

c# - Include() ThenInclude() 在 Table Per Hierarchy 策略中抛出 "Sequence contains more than one matching element"异常