Regex not matching words ending with “Impl”

馋奶兔 提交于 2021-01-29 10:04:45

问题


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.

I tried

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

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

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


回答1:


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)

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')


来源:https://stackoverflow.com/questions/22964598/regex-not-matching-words-ending-with-impl

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!