正则表达式匹配括号包围不是一个字符串 [英] Regex to match a string NOT surrounded by brackets
问题描述
我要解析文本,其中的与的是一个关键的词,如果它不是用方括号包围。我要匹配关键字的与的。还有,必须在两侧字边界的与的
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屋!