正则表达式中的特殊字符

public static final String specialChars1= "\\W\\S"; String str2 = str1.replaceAll(specialChars1, "").replace(" ", "+"); public static final String specialChars2 = "`~!@#$%^&*()_+[]\\;\',./{}|:\"?"; String str2 = str1.replaceAll(specialChars2, "").replace(" ", "+"); 

无论str1是什么,我都希望删除除字母和数字之外的所有字符,并将空格替换为加号( + )。

我的问题是,如果我使用specialChar1 ,它不会删除一些字符,如;'" ,如果我使用specialChar2它会给我一个错误:

 java.util.regex.PatternSyntaxException: Syntax error U_REGEX_MISSING_CLOSE_BRACKET near index 32: 

怎么能实现这个目标? 我搜索过但找不到完美的解决方案。

这对我有用:

String result = str.replaceAll("[^\\dA-Za-z ]", "").replaceAll("\\s+", "+");

对于此输入字符串:

/ – +!@#$%^& ())“;:[] {} \ | wetyk 678dfgh

它产生了这个结果:

+ wetyk + 678dfgh

replaceAll期待一个正则表达式:

 public static final String specialChars2 = "[`~!@#$%^&*()_+[\\]\\\\;\',./{}|:\"<>?]"; 

你的第一个正则表达式的问题是"\W\S"意味着找到一个由两个字符组成的序列,第一个字符不是字母或数字后跟一个不是空格的字符。

你的意思是"[^\w\s]" 。 这意味着:找到既不是字母也不是数字或空格的单个字符。 (我们不能使用"[\W\S]"因为这意味着找到一个不是字母或数字的字符或不是空格 – 这基本上都是可打印的字符)。

第二个正则表达式是一个问题,因为您尝试使用保留字符而不转义它们。 您可以将它们放在[] ,其中大多数字符(不是全部)没有特殊含义,但整个事情看起来非常混乱,您必须检查您是否没有错过任何标点符号。

例:

 String sequence = "qwe 123 :@~ "; String withoutSpecialChars = sequence.replaceAll("[^\\w\\s]", ""); String spacesAsPluses = withoutSpecialChars.replaceAll("\\s", "+"); System.out.println("without special chars: '"+withoutSpecialChars+ '\''); System.out.println("spaces as pluses: '"+spacesAsPluses+'\''); 

这输出:

 without special chars: 'qwe 123 ' spaces as pluses: 'qwe+123++' 

如果你想将多个空格组合成一个+那么使用"\s+"作为你的正则表达式(记得逃避斜线)。

我有一个类似的问题要解决,我使用以下方法:

 text.replaceAll("\\p{Punct}+", "").replaceAll("\\s+", "+"); 

代码与时间基准标记

 public static String cleanPunctuations(String text) { return text.replaceAll("\\p{Punct}+", "").replaceAll("\\s+", "+"); } public static void test(String in){ long t1 = System.currentTimeMillis(); String out = cleanPunctuations(in); long t2 = System.currentTimeMillis(); System.out.println("In=" + in + "\nOut="+ out + "\nTime=" + (t2 - t1)+ "ms"); } public static void main(String[] args) { String s1 = "My text with 212354 digits spaces and \n newline \t tab " + "[`~!@#$%^&*()_+[\\\\]\\\\\\\\;\\',./{}|:\\\"<>?] special chars"; test(s1); String s2 = "\"Sample Text=\" with - minimal \t punctuation's"; test(s2); } 

样本输出

 In=My text with 212354 digits spaces and newline tab [`~!@#$%^&*()_+[\\]\\\\;\',./{}|:\"<>?] special chars Out=My+text+with+212354+digits+spaces+and+newline+tab+special+chars Time=4ms In="Sample Text=" with - minimal punctuation's Out=Sample+Text+with+minimal+punctuations Time=0ms 

你可以使用这样的正则表达式:

[<#![CDATA[¢<(+|!$*);¬/¦,%_>? :#=“〜{@} \]]]#>]`

首先删除“#”,然后从表达式结束

问候

@npinti

使用“\ w”与“\ dA-Za-z”相同

这对我有用:

 String result = str.replaceAll("[^\\w ]", "").replaceAll("\\s+", "+");