C# 中的正则表达式 OR 运算符问题
我想匹配一个模式 [0-9][0-9]KK[az][az]
,该模式前面没有这些单词
http://
example
我有一个正则表达式,它处理第一个条件,但不处理第二个条件。
不使用 OR 运算符
var body = Regex.Replace(body, "(?<!http://([\\w+?\\.\\w+])+([a-zA-Z0-9\\~\\!\\@\\#\\$\\%
\\^\\&\\*\\(\\)_\\-\\=\\+\\\\\\/\\?\\.\\:\\;\\'\\,]*)?)([0-9][0-9]KK[a-z][a-z])
(?!</a>)","replaced");
使用 OR 运算符
var body = Regex.Replace(body, "(?example)|(?<!http://([\\w+?\\.\\w+])+([a-zA-Z0-9\\~\\!\\@
\\#\\$\\%\\^\\&\\*\\(\\)_\\-\\=\\+\\\\\\/\\?\\.\\:\\;\\'\\,]*)?)([0-9][0-9]KK[a-
z][a-z])(?!</a>)","replaced");
第二个使用 OR 运算符会引发异常。我该如何解决这个问题?
它不应与以下任何一个匹配:
example99KKas
I want to match a pattern [0-9][0-9]KK[a-z][a-z]
which is not preceded by either of these words
http://
example
I have a RegEx which takes care of the first criteria, but not the second criteria.
Without OR operator
var body = Regex.Replace(body, "(?<!http://([\\w+?\\.\\w+])+([a-zA-Z0-9\\~\\!\\@\\#\\$\\%
\\^\\&\\*\\(\\)_\\-\\=\\+\\\\\\/\\?\\.\\:\\;\\'\\,]*)?)([0-9][0-9]KK[a-z][a-z])
(?!</a>)","replaced");
wth OR Operator
var body = Regex.Replace(body, "(?example)|(?<!http://([\\w+?\\.\\w+])+([a-zA-Z0-9\\~\\!\\@
\\#\\$\\%\\^\\&\\*\\(\\)_\\-\\=\\+\\\\\\/\\?\\.\\:\\;\\'\\,]*)?)([0-9][0-9]KK[a-
z][a-z])(?!</a>)","replaced");
The second one with OR operator throws an exception. How can I fix this?
It should not match either of these:
example99KKas
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这是一种方法。从字符串的开头开始,检查每个字符是否不是
'http://'
或'example'
的开头。懒洋洋地这样做,一次一个字符,这样我们就能在到达这个神奇的单词时发现它。另外,捕获魔术词之前的所有内容,以便我们可以将其放回替换字符串中。这里它处于注释自由间距模式,以便普通人也能理解:请注意,这对于魔术词区分大小写,但对于
http://
和example.另请注意,这是未经测试的(我不知道 C# - 只是它的正则表达式引擎)。
"var body = ..."
中的"var"
对我来说看起来有点可疑。 ??Here is one way to do it. Start at the beginning of the string and check that each character is not the start of
'http://'
or'example'
. Do this lazily, and one character at a time so that we can spot the magic word once we reach it. Also, capture everything up to the magic word so that we can put it back in the replacement string. Here it is in commented free-spacing mode so that it can be comprehended by mere mortals:Note that this is case sensitive for the magic word but not for
http://
andexample
. Note also that this is untested (I don't know C# - just its regex engine). The"var"
in"var body = ..."
looks kinda suspicious to me. ??我无法让第二个示例正常工作,它给出了“无法识别的分组构造”的 ArgumentException。
但我替换了 url 匹配并稍微移动了第一个替代组并想出了这个:
I wasn't able to get the second example working, it gave an ArgumentException of "Unrecognized grouping construct".
But I replaced the url matching and moved the first alternative group a bit and came up with this:
你可以使用这样的东西:
You could use something like this: