正则表达式在java中的特殊字符(Regex for special characters in j

2019-06-24 08:01发布

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:

这怎么可能,以实现? 我已经搜查,但未能找到一个完美的解决方案。

Answer 1:

这为我工作:

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

对于这种输入字符串:

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

它得到这样的结果:

+ + Wetyk 678dfgh



Answer 2:

replaceAll需要一个正则表达式:

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


Answer 3:

你的第一个正则表达式的问题,是"\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+"作为您的正则表达式,而不是(记住逃脱斜线)。



Answer 4:

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

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


Answer 5:

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

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

除去“#”在第一和在从表达端

问候



Answer 6:

@npinti

使用 “\ W” 是相同的 “\ DA-ZA-Z”

这为我工作:

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


文章来源: Regex for special characters in java