c# - 正则表达式匹配不被方括号包围的字符串

标签 c# regex

我必须解析一个文本,其中 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/

相关文章:

c# - 大datagridview导出到excel

c# - 不显示 .net 对象的属性和方法

c# - 检查斜杠的字符串

regex - 为什么 Perl 的 m//g 运算符有时会导致在文本中引入 NULL?

c# - 从 C# 中的唯一(独立)元素获取索引

c# - 如何在不尊重某些字符的情况下对列表进行排序?

c# - 这个 C# 字符串格式是什么意思?

java - 正则表达式无法在java中找到重复标记

windows - 如何使用bat文件脚本替换文本文件中的文本?

c# - 短代码正则表达式