Using Java Regex, how to check if a string contains any of the words in a set ?

后端 未结 3 457
面向向阳花
面向向阳花 2020-12-13 04:27

I have a set of words say -- apple, orange, pear , banana, kiwi

I want to check if a sentence contains any of the above listed words, and If it does , I want to f

3条回答
  •  伪装坚强ぢ
    2020-12-13 04:44

    I don't think a regexp will do a better job in terms of performance but you can use it as follow:

    Pattern p = Pattern.compile("(apple|orange|pear)");
    Matcher m = p.matcher(inputString);
    while (m.find()) {
       String matched = m.group(1);
       // Do something
    }
    

提交回复
热议问题