如何在字符串文本中搜索单词,这个单词结束"。"或","在java中

时间:2017-02-15 13:48:26

标签: java string search

有人可以帮我代码吗? 如何在字符串文本中搜索单词,这个单词结束"。"或","在java中

我不希望这样的搜索找到它

String word = "test.";

String wordSerch = "I trying to tasting the Artestem test.";

String word1 = "test,"; // here with ","

String word2 = "test."; // here with "."

String word3 = "test";  //here without 

//after i make string array and etc...

if((wordSearch.equalsIgnoreCase(word1))||
   (wordSearch.equalsIgnoreCase(word2))||
   (wordSearh.equalsIgnoreCase(word3))) {
}

if (wordSearch.contains(gramer)) 
//it's not working because the word Artestem  will contain test too, and I don't need it

5 个答案:

答案 0 :(得分:1)

您可以将matches(Regex)函数与字符串

一起使用
String word = "test.";
boolean check = false;
if (word.matches("\w*[\.,\,]") {
    check = true;
}

答案 1 :(得分:1)

您可以使用正则表达式

Matcher matcher = Pattern.compile("\\btest\\b").matcher(wordSearch);
if (matcher.find()) {
}

\\b\\b只匹配一个字。因此"Artestem"在这种情况下不匹配。 如果您的句子中有matcher.find()字,则true会返回test,否则会false

答案 2 :(得分:1)

String stringToSearch = "I trying to tasting the Artestem test.   test,";

Pattern p1 = Pattern.compile("test[.,]");
Matcher m = p1.matcher(stringToSearch);

while (m.find())
{
    System.out.println(m.group());   
}

答案 3 :(得分:0)

什么是单词? E.g:

  1. '5'一个字?
  2. '汉语'是一个词,还是两个字?
  3. '纽约'一句话,还是两个字?
  4. 'Kraftfahrzeughaftpflichtversicherung'(意为“汽车责任保险”)一个字,还是3个字?
  5. 对于某些语言,您可以使用Pattern.compile("[^\\p{Alnum}\u0301-]+")来分割单词。请使用Pattern#split

    我想,你可以通过这种模式找到词:

    String notWord = "[^\\p{Alnum}\u0301-]{0,}";
    Pattern.compile(notWord  + "test" + notWord)` 
    

    另请参阅:https://docs.oracle.com/javase/6/docs/api/java/util/regex/Pattern.html

答案 4 :(得分:0)

你可以将一个数组中的字符串转换为单词(使用" split"),并搜索该数组,使用要查找的字符检查单词的最后一个字符(charAt)

String stringtoSearch = "This is a test.";
String whatIwantToFind = ",";

String[] words =  stringtoSearch.split("\\s+");
for (String word : words) {
    if (whatIwantToFind.equalsignorecas(word.charAt(word.length()-1);)) {
        System.out.println("FIND");

    }
}