Java String replaceAll
Hi All,
I am trying the following code line:
str.replaceAll("&", "&");
But Its not giving me the proper results. Seems that "&" in the string is never matched. As the first parameter, needs to be regex for this method. I tried various options, but it didnt work out.
Could someone please help me out to check the correct useage in this scenario.
Thanks in Advance.
> Hi All,
>
> I am trying the following code line:
>
>str.replaceAll("&", "&");
You want to replace all "&" with "&"?
> But Its not giving me the proper results.
What is the proper result and what is the result you expect. Give examples please.
> Seems that
> "&" in the string is never matched. As the first
> parameter, needs to be regex for this method. I tried
> various options, but it didnt work out.
What did you try? What does "didn't work" mean? Did you get no output? output that you didn't expect?
My memory is bad, but I think & is a special char in the replace rather than the search.Not that replaceAll( "&", "&" ) would do anything.
mlka at 2007-7-15 23:27:14 >

You don't need to construct the string with +s.Try this You may only need to \\ one of the &s, as mlk suggests. First see if this works, then experiment:str = str.replaceAll("\\&", "\\&");
Thanks for quick replies. I guess the & and & confusion has got cleared with my last post.
I tried following options :
string abc = "&" + "amp" + ";" ;
1. str.replaceAll("[&]", abc);
2. str.replaceAll(Pattern.compile("&").toString(), abc);
3. str.replaceAll("\\p{&}", abc);
Some other similar to the above....
You don't need to construct the string with +s.
Try this You may only need to \\ one of the &s, as mlk suggests. First see if this works, then experiment:
str = str.replaceAll("\\&", "\\&");
Note that you can't just do str.replaceAll(...)
since Strings are immutable.
In fact, that may be the only problem and the & may have nothing to do with it.