用于否定匹配结束的正则表达式
我需要一个正则表达式来匹配不以某些术语结尾的字符串。
输入是一堆类名,例如 Foo
、FooImpl
、FooTest
、FooTestSuite
等。
我想匹配任何不以 Test
、Tests
或 TestSuite
结尾的内容。
应匹配:
FooImpl
FooTestImpl
Foo
不应匹配:
FooTest
FooTestSuite
FooTests
我就是做不到这一点。我现在拥有的内容是错误的,所以我什至懒得发布它。
I need a regex to match strings that do not end in certain terms.
Input is a bunch of Class names, like Foo
, FooImpl
, FooTest
, FooTestSuite
, etc.
I want to match anything that does not end in Test
, Tests
, or TestSuite
.
Should Match:
FooImpl
FooTestImpl
Foo
Should not match:
FooTest
FooTestSuite
FooTests
I just can't get this right. What I have now is wrong so I won't even bother posting it.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
如果您的语言支持,请尝试使用负向后查找:
否则,您可以使用负向前查找来模拟负向后查找:
Rubular
Try a negative lookbehind if your language supports it:
Otherwise you can simulate a negative lookbehind using a negative lookahead:
Rubular
负匹配在很大程度上是正则表达式实际上无法做到的。有什么原因你可以这样做 !(string =~ regex) 吗?
这就是 grep 有一个 -v (反向匹配)标志的原因。
Negative matching is something regex can't actually do for the most part. Is there some reason you can just do !(string =~ regex)?
That's why grep has a -v (invert match) flag.
我提出了使用 grep 的替代解决方案:
grep -vE ".+(Test|Tests|TestSuite)$" *
-v
是否定,-E 用于正则表达式匹配。由于并非所有语言都支持向前查找和向后查找,并且 grep 基本上与平台无关,因此它可能是您最好的选择。
I propose an alternative solution using grep:
grep -vE ".+(Test|Tests|TestSuite)$" *
-v
is negation,-E
is for regex matching. Since not all languages support lookaheads and lookbehinds and grep is mostly platform independent, it could be your best bet.您可以尝试使用单词边界运算符:
这将定位以这些字符结尾的单词。
You might try using a word boundary operator:
That will target words that end with those characters.