Groovy字符串比较

时间:2013-07-03 19:11:03

标签: string groovy string-comparison

我需要知道两个字符串是否“匹配”,其中“匹配”基本上意味着两个字符串之间存在显着重叠。例如,如果string1是“foo”而string2是“foobar”,那么这应该是匹配的。如果string2是“barfoo”,那也应该与string1匹配。但是,如果string2是“fobar”,则不应该匹配。我很难找到一个聪明的方法来做到这一点。我是否需要先将字符串拆分为字符列表,还是有办法在Groovy中进行这种比较?谢谢!

2 个答案:

答案 0 :(得分:4)

使用Apache commons StringUtils:

@Grab( 'org.apache.commons:commons-lang3:3.1' )
import static org.apache.commons.lang3.StringUtils.getLevenshteinDistance

int a = getLevenshteinDistance( 'The quick fox jumped', 'The fox jumped' )
int b = getLevenshteinDistance( 'The fox jumped', 'The fox' )

// Assert a is more similar than b
assert a < b

Levenshtein Distance告诉您一个字符串变为另一个字符串必须更改的字符数

因此,要从'The quick fox jumped'转到'The fox jumped',您需要删除6个字符(因此得分为6)

要从'The fox jumped'转到'The fox',您需要删除7个字符。

答案 1 :(得分:1)

根据您的示例,普通的String.contains可能就足够了:

assert 'foobar'.contains('foo')
assert 'barfoo'.contains('foo')
assert !'fobar'.contains('foo')
相关问题