我必须解析一个文本,其中 with 是一个关键词,如果它没有被方括号括起来的话。我必须将关键字 与 匹配。此外,with 的两边必须有单词边界。
以下是一些 with 不是关键字的示例:
- [与]
- [与]
- [一些文本与一些文本]
- [一些文字]
- [带有一些文字]
这里有一些例子,其中 with 是关键字
- 与
- ] 与
- 你好
- 世界你好
- 你好[世界],你好
- 你好[世界]和你好[世界]
有人帮忙吗? 提前致谢。
最佳答案
您可以查找单词 with
并看到最靠近其左侧的括号不是左括号,并且最靠近其右侧的括号不是右括号:
Regex regexObj = new Regex(
@"(?<! # Assert that we can't match this before the current position:
\[ # An opening bracket
[^[\]]* # followed by any other characters except brackets.
) # End of lookbehind.
\bwith\b # Match ""with"".
(?! # Assert that we can't match this after the current position:
[^[\]]* # Any text except brackets
\] # followed by a closing bracket.
) # End of lookahead.",
RegexOptions.IgnorePatternWhitespace);
Match matchResults = regexObj.Match(subjectString);
while (matchResults.Success) {
// matched text: matchResults.Value
// match start: matchResults.Index
// match length: matchResults.Length
matchResults = matchResults.NextMatch();
}
环视表达式不会在换行符处停止;如果您希望单独评估每一行,请使用 [^[\]\r\n]*
而不是 [^[\]]*
。
关于c# - 正则表达式匹配不被方括号包围的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7005784/