Replace escaped escape sequence with unequal value

As input, I get the line "some text\\nsome text"→, which is displayed as "some text\nsome text". How can I remove one backslash and get "some text\nsome text"→ shown as

"some text
some text"

This will work for other special characters such as "\t"? With regex can only be done as   textLine.replace("\\n", "\n") and so on.

Is there another way?

+3
source share
4 answers

. org.apache.commons.lang3.StringEscapeUtils unescape Java. Unescapes Java, String. , "\" "n" , "\" "\" . unescape .

import static org.apache.commons.lang3.StringEscapeUtils.unescapeJava;

public class Unescape {
    public static void main(String[] args) {
        System.out.println("some text\\nsome text");
        System.out.println(unescapeJava("some text\\nsome text"));
    }
}

some text\nsome text
some text
some text
+8

, char .

:

    String res="";
    boolean backslash=false;
    for(char c : "some text\\nsome text".toCharArray()){
        if(c!='\\'){
            if(backslash){
                switch(c){
                    case 'n' :
                        res+='\n';
                        break;
                    case 't' :
                        res+='\t';
                        break;

                }
                backslash=false;
            }else{
                res+=c;
            }
        }
        else{
            backslash=true;
        }
    }

, , , (EOL Tab).

NB: String StringBuilder, .

0

? :

Pattern.compile("^([0-9]+).*", Pattern.MULTILINE);

http://www.javamex.com/tutorials/regular_expressions/multiline.shtml

-1

All Articles