2013-03-25 80 views
0

我试图找到一个字符串中的单词。但是,由于一段时间它不能识别一个词。我试图删除标点符号,但它似乎没有效果。我在这里错过了什么吗?这是我正在使用的代码行:s.replaceAll(“([a-z] +)[?:!。,;] *”,“$ 1”);删除标点符号问题

String test = "This is a line about testing tests. Tests are used to examine stuff"; 
    String key = "tests"; 
    int counter = 0; 


    String[] testArray = test.toLowerCase().split(" "); 

    for(String s : testArray) 
    { 
     s.replaceAll("([a-z] +) [?:!.,;]*","$1"); 
     System.out.println(s); 
     if(s.equals(key)) 
     { 
      System.out.println(key + " FOUND"); 
      counter++; 
     } 
    } 

    System.out.println(key + " has been found " + counter + " times."); 
} 

我设法找到一个解决方案(尽管可能不是理想的)通过使用S = s.replaceAll( “\ W”, “”);感谢大家指导如何解决这个问题。

+0

看看这个问题,选择答案: [http://stackoverflow.com/questions/767759/occurences-of-substring-in-a-string][1] [1]:http://stackoverflow.com/questions/767759/occurences-of-substring-in-a-string – 2013-03-25 16:00:22

回答

1

你也可以利用分割操作中的正则表达式。试试这个:

String[] testArray = test.toLowerCase().split("\\W+"); 

这将分裂的撇号,所以你可能需要用字符的具体名单来调整它一下。

+0

谢谢,也有类似的答案 – Calgar99 2013-03-25 16:23:35

1

Strings是不可变的。您需要的replaceAll结果分配给新String

s = s.replaceAll("([a-z] +)*[?:!.,;]*", "$1"); 
         ^

而且您正则表达式需要一个空间的字和标点之间。在tests.的情况下,这是不正确的。你可以用一个可选的(零个或多个)字符来调整你的regex来解决这个问题。

+0

我试过这也是无济于事。 – Calgar99 2013-03-25 15:56:04

+0

如果还试过“” – Calgar99 2013-03-25 15:57:51

0

你的正则表达式似乎并不像你想要的那样工作。 如果你想找到一些东西,之后有一段那么这将工作

([a-z]*) [?(:!.,;)*] 

返回“测试”。当它在给定的字符串上运行时。

而且

[?(:!.,;)*] 

只是指出这将然后可以更换的标点符号。

但是我不知道你为什么不使用substring()函数。