用单个 space 替换字符串中的多个字符

Replacing multiple char from String with single space

我想用单个 space.

替换给定字符串中的多个字符

例如:He is a very very good boy, isn't he? 应替换为

He
is
a
very
very
good
boy
isn
t
he 

我的密码是

String str = "He is a very very good boy, isn't he?"
String str2 = str.replaceAll("![,?.\_'@+] +"," ");
 String []tokens = str2.split(" +");

for(int i = 0; i< tokens.length; i++)
       System.out.println(tokens[i]);

但是输出是

He
is
a
very
very
good
boy,
isn't
he?

如果可能请更正我的代码或建议新代码。

这是一篇很棒的文章:Replace All Method

如果您只想在字符串中包含字母,并用 space 替换其他所有内容,则语句如下:

str2 = str.replaceAll("[^a-zA-z]", " ");

如果你想替换你提到的字符(不包括括号),使用这个:

s1 = s1.replaceAll("[^[!,?._'@+]]", " ");

如果要包含括号,请使用:

s1 = s1.replaceAll("[^[!,?._'@+\[\]]]", " ");

希望对您有所帮助!

如果你只想用字母替换那么

String x = sequence.replaceAll("[^a-zA-Z] +"," ");

还有字母和数字

String y = sequence.replaceAll("[^a-zA-Z0-9] +"," ");

看看 Replace() and ReplaceAll() 方法

首先,我认为您的正则表达式缺少转义符。我认为您想在表达式中包含反斜杠 \,但您必须像这样转义它:\.

此外,您的正则表达式 "![,?.\_'@+] +" 表示您要替换感叹号 !、属于包含 ,、[= 15=、.\_'@+,以及一个或多个 space s (+) 由单个 space.

正则表达式 [,'?]+ 应该可以完成这项工作。您可以在 Regular expressions.

阅读更多关于如何形成正确表达式的信息

我尝试了以上所有方法,但这个有效。

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

 BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String S = br.readLine();
List<String> splitted = new ArrayList<>(Arrays.asList(S.split("[ :#$%^&/<>{}*|;_()!,?.'@+\\\[\]\\"]+")));
splitted.removeAll(Arrays.asList(null,""));
System.out.println(splitted.size());
for (String word: splitted) System.out.println(word);

这是我发布的整个问题的解决方案。