我有正则表达式:(?ms)(?<attribute>\[.+?\]|public|private|\s)+?class
我有文字:
[attribute]
public int a;
[attribute C]
[attribute B]
public class Test{
}
我想知道为什么我发布的正则表达式匹配:
[attribute]
public int a;
[attribute C]
[attribute B]
public class
我认为它应该匹配:
[attribute C]
[attribute B]
public class
如果我错了,请纠正我。我认为正则表达式的读取方式是:
Find either an attribute ( [ some attribute ] ) or public key word or private keyword or space.
因此,正则表达式引擎首先应匹配 [attribute],然后是 '\n'(换行),然后是 public
关键词。在这些之后,关键字 int
不是一个选项,那为什么它会匹配它呢?
最佳答案
问题是您使用的点可以匹配任何内容,包括右方括号、空格和(在单行模式下)换行符:
\[.+?\]
你应该使用这个:
\[[^\]]+\]
说明:
\[ Match a literal open square bracket. [^\]] Match any character except a close square bracket. + One or more. \] Match a literal close square bracket.
关于c# - 为什么以下正则表达式与此文本匹配?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11660614/