Re: String.replaceAll won't work :s

From: Stefan Waldmann (stefan.k.waldmann_at_vr-web.de)
Date: 07/01/04


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



Relevant Pages

  • Re: Fastest way to search a string for the occurance of a word??
    ... but the OP's question was what's the "Fastest way to search a string ... in all the tests I did here, the Regex was by far superior. ... However, of course, if you've got new regular expressions all ... Sure - but just that extra Match object could be relevant if the search ...
    (microsoft.public.dotnet.languages.csharp)
  • Re: Search for multiple things in a string
    ... >>> As far as readability, it has nothing to do with Regular Expressions ... > and Regex. ... >> characters in the string, perhaps even writing your own state machine ...
    (microsoft.public.dotnet.languages.csharp)
  • Re: regex test failing in form validation
    ... If you have debug on you'll see a decent report of what the code is ... The regex for matching correct protocol and TLD for the URL ... This will search for the string "TLDlist". ... neither in strings nor regular expressions. ...
    (comp.lang.javascript)
  • Re: Regular Experssion
    ... that regular expressions are so powerful, how come Cor was able to whip up a ... didn't whip up a regex example to show how much faster and cooler regex is? ... <flame off> ... especially if search and match string are long. ...
    (microsoft.public.vstudio.general)
  • Re: Regular Experssion
    ... that regular expressions are so powerful, how come Cor was able to whip up a ... didn't whip up a regex example to show how much faster and cooler regex is? ... <flame off> ... especially if search and match string are long. ...
    (microsoft.public.dotnet.general)