简体   繁体   中英

java - Escape text into JavaFX code

I'm making a Java program that takes some text as input,
and has to produce the equivalent JavaFX code (a String literal). For instance:

The input is the following text:

 Hello World: This. \ is a backslash: And this.  {} are brackets. 

And the resulting JavaFX code is:

 "Hello World: This. \\ is a backslash:\nAnd this. \{\} are brackets."

Is there any native way (for example, using JavaFX SDKs) to achieve this?
If not, can someone give me the complete escaped sequences list in JavaFX?

According to the JavaFX specification , the only characters that you have to escape with a backslash when using double quotation marks are:

  • "
  • {
  • }
  • \

Here's a Java method that should do what you're looking for:

public String escapeInput(String[] input) {
    String[] characters = {"\"", "\\", "{", "}"};
    StringBuilder sb = new StringBuilder();
    sb.append("\"");
    for (String line : input) {
        for (String test : characters) {
            line = line.replace(test, "\\" + test);
        }
        sb.append(line);
        sb.append("\n");
    }
    sb.append("\"");
    return sb.toString();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM