How to unescape a Java string literal in Java?

后端 未结 11 2000
庸人自扰
庸人自扰 2020-11-22 01:35

I\'m processing some Java source code using Java. I\'m extracting the string literals and feeding them to a function taking a String. The problem is that I need to pass the

11条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-11-22 02:15

    I know this question was old, but I wanted a solution that doesn't involve libraries outside those included JRE6 (i.e. Apache Commons is not acceptable), and I came up with a simple solution using the built-in java.io.StreamTokenizer:

    import java.io.*;
    
    // ...
    
    String literal = "\"Has \\\"\\\\\\\t\\\" & isn\\\'t \\\r\\\n on 1 line.\"";
    StreamTokenizer parser = new StreamTokenizer(new StringReader(literal));
    String result;
    try {
      parser.nextToken();
      if (parser.ttype == '"') {
        result = parser.sval;
      }
      else {
        result = "ERROR!";
      }
    }
    catch (IOException e) {
      result = e.toString();
    }
    System.out.println(result);
    

    Output:

    Has "\  " & isn't
     on 1 line.
    

提交回复
热议问题