Regex for special characters in java

后端 未结 6 1644
说谎
说谎 2021-01-06 10:09
public static final String specialChars1= \"\\\\W\\\\S\";
String str2 = str1.replaceAll(specialChars1, \"\").replace(\" \", \"+\");

public static final String speci         


        
6条回答
  •  失恋的感觉
    2021-01-06 10:47

    I had a similar problem to solve and I used following method:

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

    Code with time bench marking

    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);
    }
    

    Sample Output

    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
    

提交回复
热议问题