Text cleaning and replacement: delete \n from a text in Java

后端 未结 9 1931
我在风中等你
我在风中等你 2020-12-08 19:57

I\'m cleaning an incoming text in my Java code. The text includes a lot of \"\\n\", but not as in a new line, but literally \"\\n\". I was using replaceAll() from the String

相关标签:
9条回答
  • 2020-12-08 20:54

    Instead of String.replaceAll(), which uses regular expressions, you might be better off using String.replace(), which does simple string substitution (if you are using at least Java 1.5).

    String replacement = string.replace("\\n", "");
    

    should do what you want.

    0 讨论(0)
  • 2020-12-08 20:56

    The other answers have sufficiently covered how to do this with replaceAll, and how you need to escape backslashes as necessary.

    Since 1.5., there is also String.replace(CharSequence, CharSequence) that performs literal string replacement. This can greatly simplify many problem of string replacements, because there is no need to escape any regular expression metacharacters like ., *, |, and yes, \ itself.

    Thus, given a string that can contain the substring "\n" (not '\n'), we can delete them as follows:

    String before = "Hi!\\n How are you?\\n I'm \n   good!";
    System.out.println(before);
    // Hi!\n How are you?\n I'm 
    //   good!
    
    String after = before.replace("\\n", "");
    
    System.out.println(after);
    // Hi! How are you? I'm 
    //   good!
    

    Note that if you insist on using replaceAll, you can prevent the ugliness by using Pattern.quote:

    System.out.println(
        before.replaceAll(Pattern.quote("\\n"), "")
    );
    // Hi! How are you? I'm 
    //   good!
    

    You should also use Pattern.quote when you're given an arbitrary string that must be matched literally instead of as a regular expression pattern.

    0 讨论(0)
  • 2020-12-08 20:59
    string = string.replaceAll(""+(char)10, " ");
    
    0 讨论(0)
提交回复
热议问题