java字符匹配,Java:匹配字符串中的短语

I have a list of phrases (phrase might consist of one or more words) in a database and an input string. I need to find out which of those phrases appear in the input string.

Is there an efficient way to perform such matching in Java?

解决方案

A quick hack would be:

Build a regexp based on the combined phrases

Construct a set listing the phrases that haven't matched so far

Repeatedly run find until all phrases have been found or end of input is reached, removing matches from the set of remaining phrases to find

That way, the input is traversed only once, regardless how many phrases you provide. If the regexp compiler generates an efficient matcher for multiple alternatives, this should yield decent performance. However, this depends a lot on your phrases and input string, as well as the quality of the Java regexp engine.

Sample code (tested, but not optimized or profiled for performance):

public static boolean hasAllPhrasesInInput(List phrases, String input) {

Set phrasesToFind = new HashSet();

StringBuilder sb = new StringBuilder();

for (String phrase : phrases) {

if (sb.length() > 0) {

sb.append('|');

}

sb.append(Pattern.quote(phrase));

phrasesToFind.add(phrase.toLowerCase());

}

Pattern pattern = Pattern.compile(sb.toString(), Pattern.CASE_INSENSITIVE);

Matcher matcher = pattern.matcher(input);

while (matcher.find()) {

phrasesToFind.remove(matcher.group().toLowerCase());

if (phrasesToFind.isEmpty()) {

return true;

}

}

return false;

}

Some caveats:

The code above will match phrases as substrings of words. If only complete words should match, you will need to add word boundaries ("\b") to the generated regexps.

The code must be modified if some phrases may be substrings of other phrases.

If you need to match non-ASCII text, you should add the regexp option Pattern.UNICODE_CASE and call toLowerCase(Locale) instead of toLowerCase(), using a suitable Locale.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值