在正则表达式(Groovy)中,“== ~”运算符与运算符类似 “==”,但匹配模式而不是“计算相等” 您能否通过一个小例子帮助我理解这两者之间的实际区别?
最佳答案
x==y
是 x.equals(y)
或 x.compareTo(y)
的缩写 - 请参阅 Groovy Operator Overloading (在java中这基本上是比较对象身份)。
运算符==~
是专门设计的比较运算符,可帮助您对字符串上的模式进行完全匹配。
为操作符生成的代码(例如 disasm 代码 'xxx' ==~/xx?/
)是:
ScriptBytecodeAdapter.matchRegex("xxx", "xx?")
来自Groovy Regular Espressions :
Since a Matcher coerces to a boolean by calling its find method, the =~ operator is consistent with the simple use of Perl's =~ operator, when it appears as a predicate (in 'if', 'while', etc.). The "stricter-looking" ==~ operator requires an exact match of the whole subject string. It returns a Boolean, not a Matcher.
关于java - 匹配模式和计算相等性之间的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27146943/