这里是Groovy 2.4.x.我有一个方法需要两个Strings
,需要对它们进行一些分析。
FIZZ
"或" BUZZ
",然后它应该返回false
FIZZ
"或" BUZZ
",然后它应该返回false
FIZZ
"或" BUZZ
",然后我们继续......
FIZZ
" /" BUZZ
&#34之前提取两个字符串的子字符串; - > "前缀" true
;否则,false
示例:
foo
" &安培; " bar
" => false
(因为两者都没有结束" FIZZ
"或" BUZZ
")foo
" &安培; " barFIZZ
" => false
(因为只有1个以" FIZZ
"或" BUZZ
")fooFIZZ
" &安培; " barBUZZ
" => false
(因为" foo
"!=" bar
")fooFIZZ
" &安培; " fooBUZZ
" => true
(因为" foo
" ==" foo
")这是我最好的尝试:
class FizzBuzzMatcher {
boolean matches(String left, String right) {
boolean matches = false
if(right.endsWith('FIZZ') || right.endsWith('BUZZ')) {
String rightPrefix
rightPrefix = right.subSequence(0, right.indexOf('FIZZ'))
if(rightPrefix.isEmpty()) {
rightPrefix = right.subSequence(0, right.indexOf('BUZZ'))
}
if(left.endsWith('FIZZ') || left.endsWith('BUZZ')) {
String leftPrefix
leftPrefix = left.subSequence(0, left.indexOf('FIZZ'))
if(leftPrefix.isEmpty()) {
leftPrefix = left.subSequence(0, left.indexOf('BUZZ'))
}
if(leftPrefix == rightPrefix) {
matches = true
}
}
}
matches
}
}
...但是你可以看到,这有点令人讨厌。这里有更优雅的解决方案?我对OSS库(Apache Commons等)开放。
答案 0 :(得分:3)
您可以尝试使用正则表达式:
pattern = ~/(.*)(FIZZ|BUZZ)/
def matches(left, right) {
def m1, m2
return (m1 = (left =~ pattern)) && (m2 = (right =~ pattern))
&& (m1[0][1] == m2[0][1])
}
有关regexp运算符的语法,请参阅http://docs.groovy-lang.org/latest/html/documentation/index.html#_regular_expression_operators