Groovy中的==~和!=有什么区别?

What is the difference between ==~ and != in Groovy?

这些有什么区别?

为什么要用一个而不用另一个?

def variable = 5
if( variable ==~ 6 && variable != 6 ) {
  return '==~ and != are not the same.'
} else {
  return '==~ and != are the same.'
}

在Java中,!=“不等于”~"bitwise NOT" 。你实际上会做 variable == ~6.

在Groovy中,==~运算符是"Regex match"。例子是:

  1. "1234" ==~ /\d+/ -> 计算结果为 true
  2. "nonumbers" ==~ /\d+/ -> 计算结果为 false

在groovy中,==~运算符(又名"match"运算符)用于正则表达式匹配。 != 只是一个普通的旧常规 "not equals"。所以这些是非常不同的。

比照。 http://groovy-lang.org/operators.html

在Groovy中你还要注意,除了==~,别名"Match operator",还有=~,别名"Find Operator"和~,别名 "Pattern operator".

全部解释here.

==~结果类型:Boolean/boolean([=43=中没有基元,一切都不是看起来的样子!)

=~ 结果类型:java.util.regex.Matcher

~ 结果类型:java.util.regex.Pattern

我假设 Groovy interpreter/compiler 可以区分用作模式运算符的 ~ 和用作 按位非 [=37] 的 ~ =] (即它在 Java 中的使用)通过上下文:前者总是跟在一个模式之后,它总是被括在定界符中,通常是 /.