| Author |
escape character nightmare - please help
|
Yuriy Zilbergleyt
Ranch Hand
Joined: Dec 13, 2004
Posts: 429
|
|
Hello, I'm trying to assign the value \" to a String. That is, I want the string to be backslash + double quote. \" just gives the double quote, \\" becomes an unterminated string, and \\\" is back to the double quote without the backslash. I'm pretty sure that unicode would have the same result. The must be some way to do this, right? Thanks in advance, Yuriy
|
 |
Ernest Friedman-Hill
author and iconoclast
Marshal
Joined: Jul 08, 2003
Posts: 24057
|
|
This works fine: String s = "\\\""; From your message, that appears to be one of the things you tried, but perhaps you made a typo?
|
[Jess in Action][AskingGoodQuestions]
|
 |
Yuriy Zilbergleyt
Ranch Hand
Joined: Dec 13, 2004
Posts: 429
|
|
Hmm, that does work. Actually what I am really trying to do is replace all occurances of double quotes in a String with the escaped double quote. So more along the lines of String test = "\"abc"; System.out.println(test.replaceAll("\"", "\\\"")); this just prints out "abc I'm guessing that this is a regular expression problem then? Thanks in advance, Yuriy
|
 |
Ernest Friedman-Hill
author and iconoclast
Marshal
Joined: Jul 08, 2003
Posts: 24057
|
|
Originally posted by Yuriy Zilbergleyt: I'm guessing that this is a regular expression problem then?
Yes. It's tricky because the backslash is meaningful to both Java and the regexp parser. To do this, first write the actual expression you want to replace with: \\" Then escape each of the special characters so they'll pass through the Java parser untouched: \\\\\" So you need to say System.out.println(test.replaceAll("\"", "\\\\\"")); Five slashes!
|
 |
Yuriy Zilbergleyt
Ranch Hand
Joined: Dec 13, 2004
Posts: 429
|
|
Great! Thank you so much! Yuriy
|
 |
Layne Lund
Ranch Hand
Joined: Dec 06, 2001
Posts: 3061
|
|
Your subject name aptly names your problem. When dealing with regular expressions, escape characters are definitely nightmarish! Layne
|
Java API Documentation
The Java Tutorial
|
 |
Stefan Wagner
Ranch Hand
Joined: Jun 02, 2003
Posts: 1923
|
|
|
It helps to read regular expressions containing special characters from a file or a textfield, and to control them by printing them out.
|
http://home.arcor.de/hirnstrom/bewerbung
|
 |
 |
|
|
subject: escape character nightmare - please help
|
|
|