开发者

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();
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜