Lex
Lex

Reputation: 169

Replace an escaped escape sequence with its unescaped value

As input I get the string "some text\\nsome text" -> so shown as "some text\nsome text". How is it possible to delete one backslash and get "some text\nsome text" -> shown as

"some text
some text"

That will work also for other special characters like "\t"? With regex it's possible to do only like textLine.replace("\\n", "\n") and so on.

Is there another way?

Upvotes: 3

Views: 9592

Answers (3)

Paul Vargas
Paul Vargas

Reputation: 42040

You don't need reinvent the wheel. You can use org.apache.commons.lang3.StringEscapeUtils for unescape Java strings. Unescapes any Java literals found in the String. For example, it will turn a sequence of '\' and 'n' into a newline character, unless the '\' is preceded by another '\'. In that case, you need unescape one more time.

Code:

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

Output:

some text\nsome text
some text
some text

Upvotes: 8

alain.janinm
alain.janinm

Reputation: 20065

So it's not so obvious, you want to create one char from two chars.

I made this method :

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

Maybe it will help you, it actually works only for the case I put in switch (EOL and Tab).

NB: Replace String with StringBuilder if you want better performance.

Upvotes: 0

user425367
user425367

Reputation:

Are you playing with multiple line regex? Then you can compile a regex:

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

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

Upvotes: 0

Related Questions