日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > java >内容正文

java

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

發布時間:2025/3/19 java 19 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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.

總結

以上是生活随笔為你收集整理的java字符匹配,Java:匹配字符串中的短语的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。