Kindly let me know how to achieve it. or in case you need more clarity.
Working with \ in Java source code can be a bit tricky, especially when dealing with regular expressions, because you have to escape the \ on multiple levels. Sometimes you need to write \\ or even \\\\ for a backslash.
Need to replace a string 11:20 with 11\:20, But when ever i try replacing the occurrences of ':' with '\:' it try escaping the '\' itself when used with "".
I don't think you're right there, but "\"s are a royal pain in the rear in Java.
Not only are they reduced by the String class (why, I have never understood), they are also interpreted by the regex compiler (which takes Strings).
Furthermore, the String class isn't consistent about its replace() methods: replace() takes a simple String, but replaceAll() and replaceFirst() take regexes.
However, the simple rule is this: Any time you want a '\' in a String you must put at least 2 of them. If the String is also a regex you have to put 4 (ugh!).
However, in your case replace(":", "\\:") should do the trick.
Winston Gutkowski wrote:Not only are they reduced by the String class (why, I have never understood)
\ is an escape character in many programming languages. Its need comes from the requirement to add certain characters in strings / chars. Without \, how would you create a String that contains ", or the character '? Now it's "\"" and '\''. It also gives you string and char literals for characters like tab (\t) and line break (\n).
Or would you prefer Visual Basic's way:
I know which one I prefer, and it's definitely not VB.
Rob Spoor wrote:\ is an escape character in many programming languages...
Sorry, I wasn't clear. I know what it's used for, I just don't know why they chose '\'; especially when it's already used by regex (not to mention Windows).
One of the other languages I use had the foresight to choose a different escape character for its Strings (in its case, '~'), which makes everything so much easier .