java 查找单词位置,如何在java中的String中查找整个单词

I have a String that I have to parse for different keywords.

For example, I have the String:

"I will come and meet you at the 123woods"

And my keywords are

'123woods'

'woods'

I should report whenever I have a match and where. Multiple occurrences should also be accounted for. However, for this one, I should get a match only on 123woods, not on woods. This eliminates using String.contains() method. Also, I should be able to have a list/set of keywords and check at the same time for their occurrence. In this example, if I have '123woods' and 'come', I should get two occurrences. Method execution should be somewhat fast on large texts.

My idea is to use StringTokenizer but I am unsure if it will perform well. Any suggestions?

解决方案

The example below is based on your comments. It uses a List of keywords, which will be searched in a given String using word boundaries. It uses StringUtils from Apache Commons Lang to build the regular expression and print the matched groups.

String text = "I will come and meet you at the woods 123woods and all the woods";

List tokens = new ArrayList();

tokens.add("123woods");

tokens.add("woods");

String patternString = "\\b(" + StringUtils.join(tokens, "|") + ")\\b";

Pattern pattern = Pattern.compile(patternString);

Matcher matcher = pattern.matcher(text);

while (matcher.find()) {

System.out.println(matcher.group(1));

}

If you are looking for more performance, you could have a look at StringSearch: high-performance pattern matching algorithms in Java.

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值