请查看以下代码
public class PuctuationRemover {
public PuctuationRemover()
{
String str = ":The red; third.fox is hungry!!! but, is he angry? doesn't! (yeah!). Call 911! system. can't access it! what the , hell . is this. people of my country, really? 123465 can^be,found.... OK . you got it? ";
String str2 = str.replaceAll("[^a-zA-Z'\\s]+", str);
System.out.println(str2);
}
public static void main(String[]args)
{
new PuctuationRemover();
}
}
预期输出
The red thirdfox is hungry but is he angry doesn't yeah Call system can't access it what the hell is this people of my country really canbefound OK you got it
我得到的输出是
:The red; third.fox is hungry!!! but, is he angry? doesn't! (yeah!). Call 911! system. can't access it! what the , hell . is this. people of my country, ..............
原始工作正则表达式为here。
这里出了什么问题?
答案 0 :(得分:2)
如果需要删除标点符号,请提供空字符串作为第二个参数,而不是原始字符串本身。 replaceAll
的第二个参数不是原始字符串,而是替换匹配的内容。变化
String str2 = str.replaceAll("[^a-zA-Z'\\s]+", str);
与
String str2 = str.replaceAll("[^a-zA-Z'\\s]+", "");
答案 1 :(得分:1)
使用字符串str2 = str.replaceAll("[^a-zA-Z'\\s]+", "")
;
你正在做String str2 = str.replaceAll("[^a-zA-Z'\\s]+", str);
。你正在替换整个原始字符串。
有关String replaceAll的更多信息,请参阅此 javadoc。
此处在public String replaceAll(String regex, String replacement)
第二个参数中,即replacement
是要替换每个匹配的字符串。
注意:最好抓住PatternSyntaxException
。
答案 2 :(得分:0)
您正在用旧字符串替换旧字符串,这意味着即使在更换字符串后也会保留相同的字符串。您需要做的是用无字符""
替换正则表达式中指定的所有字符。