2013-07-03 43 views
0

我需要知道兩個字符串「匹配」,其中「匹配」基本上意味着兩個字符串之間存在重大重疊。例如,如果string1是「foo」而string2是「foobar」,則應該是匹配的。如果string2是「barfoo」,那也應該與string1匹配。但是,如果string2是「fobar」,這不應該是匹配。我正在努力尋找一個聰明的方法來做到這一點。我是否需要首先將字符串拆分爲字符列表,或者有沒有辦法在Groovy中進行這種比較?謝謝!Groovy字符串比較

+1

可能的重複[Java中的相似字符串比較](http://stackoverflow.com/questions/955110/similarity-string-comparison-in-java) –

回答

1

按照您的例子,普通的老String.contains可能就足夠了:

assert 'foobar'.contains('foo') 
assert 'barfoo'.contains('foo') 
assert !'fobar'.contains('foo') 
3

使用Apache公地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距離告訴你,必須改變爲一個字符串的字符數成爲另一個

所以要從'The quick fox jumped''The fox jumped',你需要刪除6個字符(所以它的得分是6)

而要從'The fox jumped'得到'The fox',你需要刪除7個字符。