正则表达式匹配括号​​包围不是一个字符串 [英] Regex to match a string NOT surrounded by brackets

查看:160
本文介绍了正则表达式匹配括号​​包围不是一个字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要解析文本,其中的的是一个关键的词,如果它不是用方括号包围。我要匹配关键字的的。还有,必须在两侧字边界的

I have to parse a text where with is a key word if it is not surrounded by square brackets. I have to match the keyword with. Also, there must be word boundaries on both side of with.

下面是一些例子,其中的的不关键字:

Here are some examples where with is NOT a keyword:


  • [有]

  • [有]

  • [与sometext sometext]

  • [sometext用]

  • [与sometext]

  • [with]
  • [ with ]
  • [sometext with sometext]
  • [sometext with]
  • [with sometext]

下面是一些例子,其中的的IS关键字

Here are some examples where with IS keyword



  • ]以

  • 你好以

  • 你好与世界

  • 你好[世界]为Hello

  • 你好[世界]与你好[世界]

  • with
  • ] with
  • hello with
  • hello with world
  • hello [ world] with hello
  • hello [ world] with hello [world]

任何人帮助?
先谢谢了。

Anyone to help? Thanks in advance.

推荐答案

您可以查找单词,看到最接近支架的左边是不是一开口支架,并且最接近支架的右侧是不是一个右括号:

You can look for the word with and see that the closest bracket to its left side is not an opening bracket, and that the closest bracket to its right side is not a closing bracket:

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\\\
] *
而不是的[^ [\\ \\] *

这篇关于正则表达式匹配括号​​包围不是一个字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆