正道从字符串

正道从字符串

问题描述:

我有一个字符串,例如删除文字标点和空格: 我想要得到的结果是这样的(除去标点符号,其他符号和空格):"hello, world! am gld to see you!" 以何种方式我可以执行此操作吗?正道从字符串

我尝试用此代码将字符串拆分为单词,但它不处理正确位置上的单词和标点符号中的空格。

String[] words = text.replaceAll("[^a-zA-Z ]", "").toLowerCase().split("\\s+"); 
+2

的问题是过于宽泛。你必须先写下规则列表。 *你必须这样做,我们不能为你做。例如。因为'@'可以是'a',可以'3'是'e'吗?可以'!'是'l'(字母L)吗? – Andreas

+0

@Andreas,对不起,我的意思是,每个非字母符号都必须被删除=> gl @ d == gld。 –

以下是进行更改的代码示例。

String s = "h e l l o, world! ! am [email protected] to see you!"; 
System.out.println(s); 
s = s.replaceAll("(?<=\\b\\p{L})\\s+(?=\\p{L}\\b)", ""); // remove spaces separating single letters 
System.out.println(s); 
s = s.replaceAll("\\s+(?=\\P{L})", ""); // remove spaces before non-letters 
System.out.println(s); 
s = s.replaceAll("(\\P{L})\\1+", "$1"); // remove repeated non-letters 
System.out.println(s); 
s = s.replaceAll("@", "a"); // replace '@' with 'a' 
System.out.println(s); 

输出

h e l l o, world! ! am [email protected] to see you! 
hello, world! ! am [email protected] to see you! 
hello, world!! am [email protected] to see you! 
hello, world! am [email protected] to see you! 
hello, world! am glad to see you! 
+0

哦,但它不适用于像这样的文本:“h l l o o”。如果信件前有多个空格。 –

+1

@Twinkle_Monkey更改')\\ s('to')\\ s +('删除多个空格分隔单个字母。 – Andreas