正则表达式不匹配以"Impl"结尾的单词 [英] Regex not matching words ending with "Impl"

查看:56
本文介绍了正则表达式不匹配以"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)

旁注:此处不直接相关,但有用的是(在Java正则表达式中)后视必须具有有限的宽度-您不能使用 * + 量词,而必须使用有限的数字量词,例如 {0,99}

Side note: not directly relevant here, but useful to know is that (in Java regex) a lookbehind must have a limited width - you can't use * or + quantifiers, and must instead use limited numerical quantifiers, e.g. {0,99}


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


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"结尾的单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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