开发者

Simple way to add escape characters to a string

Does anyone have a simple tool that can convert a non-escaped string to an escaped string?

For example, I'm trying to paste the following data into a Java String datatype:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>

I manually have to add the slashes:

<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>

Then I can paste into my java code:

String xml="<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>";

Adding the slashes gets very annoying when it's a 3MB string. I know find/replace can work in a lot of tools, but I do this so o开发者_开发百科ften that I need an even faster way.

This must be a common issue. What do most developers do? I'm thinking a good Emacs macro could do the trick but I didn't see anything obvious.


If it's a 3MB string I would read it from a file instead of hard-coding it in the source code.


Regular expressions.

s/(?=["\\])/\\/g

You can fill in the character class with any other characters you want escaped.


Take a look at prin1-to-string.

For example, invoking the following command will insert/paste the most recently killed/saved/cut text as escaped-string:

(defun yank-escaped-string ()
  (interactive)
  (insert (prin1-to-string (substring-no-properties (current-kill 0)))))

Bear in mind that the escaping mechanism is for producing strings to be read by Elisp, with conventions that might be similar to your target but not exactly the same.


StringEscapeUtils is really good


Apache Betwixt includes a utility function for this purpose, here.


In support of @Mark Bayer's answer, here is a one-liner for reading the contents of a file into a String.

String s = org.apache.commons.io.FileUtils.readFileToString("someFile");

Here's the Javadoc for the Apache Commons FileUtils class.

And you can trivially implement the equivalent functionality from scratch; e.g.

StringBuilder sb = new StringBuilder();
Reader r = new BufferedReader(new FileReader("somefile"));
try {
    int ch;
    while ((ch = r.read()) != -1) {
       sb.append((char) ch);
    }
} finally {
    r.close();
}
String s = sb.toString();

Embedding monstrously large strings into source code ... even as a throw away test ... is so lame.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜