Re: String.replaceAll won't work :s
From: Stefan Waldmann (stefan.k.waldmann_at_vr-web.de)
Date: 07/01/04
- Next message: Fahd Shariff: "Re: Best way to create an array of Strings in a called method"
- Previous message: acerpower: "Re: another prob"
- In reply to: Passero: "String.replaceAll won't work :s"
- Next in thread: Passero: "Re: String.replaceAll won't work :s"
- Reply: Passero: "Re: String.replaceAll won't work :s"
- Reply: Stefan Waldmann: "Re: String.replaceAll won't work :s"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Date: Thu, 01 Jul 2004 13:08:53 +0200
Passero wrote:
> The next line gives an error in my pattern:
>
> myString = myString.replaceAll("\\","\\\\");
>
> I want to replace every \ with \\ so the pattern he has to look for is: \\
> I looked it up in the API docs and there they said that \\ is when you want
> to find a backslash so why do i get the error?
>
> java.util.regex.PatternSyntaxException: Unexpected internal error near index
> 1
>
> \
>
> ^
Hello,
the String#replaceAll(...) method expects a regular expression (regex)
as first parameter. In regular expressions the "\" has also escape
function (just like in java Strings). Thus, a regex you would write "\\"
to match a single "\". But because in java you also have to write "\\"
to get a single "\" inside the String, what you have to use is "\\\\".
So this should do what you want to achieve:
myString = myString.replaceAll("\\\\","\\\\");
Not kidding! The second parameter is no regex, but only the String which
should replace all matches of the first param. Try it.
For more information about regular expressions, read
<http://java.sun.com/docs/books/tutorial/extra/regex/>
<http://java.sun.com/j2se/1.4.2/docs/api/java/util/regex/Pattern.html>
Greetings, Stefan
- Next message: Fahd Shariff: "Re: Best way to create an array of Strings in a called method"
- Previous message: acerpower: "Re: another prob"
- In reply to: Passero: "String.replaceAll won't work :s"
- Next in thread: Passero: "Re: String.replaceAll won't work :s"
- Reply: Passero: "Re: String.replaceAll won't work :s"
- Reply: Stefan Waldmann: "Re: String.replaceAll won't work :s"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Relevant Pages
|