正则表达式不匹配以

正则表达式不匹配以

本文介绍了正则表达式不匹配以"Impl"结尾的单词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个仅允许不以 Impl 结尾的类名的正则表达式.我已经读过不以"结尾的内容可以用负的超前(?!)进行测试,但是我找不到有效的(Java)正则表达式.

I want to create a regex that allows only class names not ending with Impl. I'v read that "not ends with" could be tested with a negative lookahead (?!), but I cannot find a working (Java) regex.

我尝试了

[A-Z][A-Za-z\d]*?(?!Impl)

但它与 SomeImpl 匹配,不应该这样.

but it matches SomeImpl, what shouldn't be the case.

哪些正则表达式与以 Impl 结尾的类名不匹配?

What regex wouldn't match class names ending with Impl?

推荐答案

否定的超前行将不起作用,因为-使用 *?(懒惰的零或更多)量词-它将在 S 并在前面没有找到 Impl ,因此匹配成功.

A negative lookahead wont work because - with the *? (lazy zero-or-more) quantifier - it'll check at S and find no Impl immediately ahead so the match succeeds.

如果您更改为贪婪的量词(将 * 更改为 *?),它仍然会失败,因为您将位于字符串的末尾-没有前进".

If you changed to a greedy quantifier (change * to *?) it would still fail because you would be at the end of the string - there is no "ahead" to look at.

相反,您想在后面使用负面表情 来检查先前的内容,即

Instead you want to use a negative lookbehind to check the previous content, i.e.

[A-Z][A-Za-z\d]*(?<!Impl)

(您可能不希望 $ 结尾,具体取决于使用模式的位置)

(You may or not want $ at the end of that, depending on where the pattern is used)


但是,除非模式本身很重要(或者您必须在使用正则表达式的环境中工作),否则更简单的选项将是 String.endsWith ,如下:


But unless the pattern itself is important (or you're working in a context where you must use regex), a simpler option would be String.endsWith, like so:

! mystring.endsWith('Impl')

这篇关于正则表达式不匹配以"Impl"结尾的单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 21:52