且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

正则表达式不匹配以"Impl"结尾的单词

更新时间:2022-11-14 19:32:50

否定的超前行将不起作用,因为-使用 *?(懒惰的零或更多)量词-它将在 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')