正则表达式匹配非特定子字符串的内容
我正在寻找一种正则表达式,它将匹配以一个子字符串开头且不以某个子字符串结尾的字符串。
示例:
// Updated to be correct, thanks @Apocalisp
^foo.*(?<!bar)$
应匹配以“foo”开头且不以“bar”结尾的任何内容。 我知道 [^...] 语法,但我找不到任何可以对字符串而不是单个字符执行此操作的内容。
我专门尝试为 Java 的正则表达式执行此操作,但我之前遇到过此问题,因此其他正则表达式引擎的答案也很棒。
感谢 @Kibbee 验证这也适用于 C#。
I am looking for a regex that will match a string that starts with one substring and does not end with a certain substring.
Example:
// Updated to be correct, thanks @Apocalisp
^foo.*(?<!bar)$
Should match anything that starts with "foo" and doesn't end with "bar". I know about the [^...] syntax, but I can't find anything that will do that for a string instead of single characters.
I am specifically trying to do this for Java's regex, but I've run into this before so answers for other regex engines would be great too.
Thanks to @Kibbee for verifying that this works in C# as well.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我认为在这种情况下你需要负面回顾,如下所示:
I think in this case you want negative lookbehind, like so:
使用验证@Apocalisp的答案:
这输出了正确的答案:
Verified @Apocalisp's answer using:
This output the the right answers:
我不熟悉 Java 正则表达式,但不熟悉 模式类建议您可以使用 (?!X) 进行非捕获零宽度负向前查找(它在该位置查找不是 X 的东西,而不将其捕获为反向引用)。 所以你可以这样做:
更新:Apocalisp 是对的,你想要负面的lookbehind。 (您正在检查 .* 匹配的内容是否不以 bar 结尾)
I'm not familiar with Java regex but documentation for the Pattern Class would suggest you could use (?!X) for a non-capturing zero-width negative lookahead (it looks for something that is not X at that postision, without capturing it as a backreference). So you could do:
Update: Apocalisp's right, you want negative lookbehind. (you're checking that what the .* matches doesn't end with bar)
正如其他评论者所说,你需要负面的展望。 在 Java 中,您可以使用以下模式:
first_string
As other commenters said, you need a negative lookahead. In Java you can use this pattern:
first_string