本文介绍了如何否定Groovy Match运算符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

文档提到了三种正则表达式特定的运算符:

The documentation mentions three regex specific operators:

  • 返回一个 Pattern
  • =〜重设 Matcher
  • ==〜返回一个 boolean
  • ~ returning a Pattern
  • =~ returing a Matcher
  • ==~ returning a boolean

现在,我该如何否定最后一个?(我同意其他人不能有任何有意义的否定.)

Now, how can I negate the last one? (I agree that the others can't have any meaningful negation.)

我尝试了显而易见的想法:

I tried the obvious thinking:

println 'ab' ==~ /^a.*/ // true: yay, matches, let's change the input
println 'bb' ==~ /^a.*/ // false: of course it doesn't match, let's negate the operator
println 'bb' !=~ /^a.*/ // true: yay, doesn't match, let change the input again
println 'ab' !=~ /^a.*/ // true: ... ???

我猜最后两个应该这样解释:

I guess the last two should be interpreted like this rather:

println 'abc' != ~/^b.*/

在这里我可以看到 new String("abc")!= new Pattern("^ b.*") true .

推荐答案

AFAIK,在Groovy中没有否定的正则表达式匹配运算符.

AFAIK, there is no negated regular expression match operator in Groovy.

所以-正如cfrick已经提到的-最好的答案似乎是否定整个表达式:

So - as already mentioned by cfrick - it seems that the best answer is to negate the whole expression:

println !('bb' ==~ /^a.*/)

另一种解决方案是反转正则表达式,但在我看来,它的可读性较差:

Another solution is to invert the regular expression, but it seems to me to be less readable:

如何在JavaScript中转换正则表达式?

这篇关于如何否定Groovy Match运算符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-16 00:49