Hi,
I am trying to use a Pattern to match certain strings in error
messages in our application. We are delimiting them using the
following notation, {0}, {1}, etc. I am trying to use String's
replaceFirst (even replaceAll) method to replace the instances of
these tokens with appropriate Strings. I am using the following code:
String match = "\\{0\\}";
String message = "{0} should be 5 characters in length.";
String replacement = "Zip Code";
message.replaceAll( match, replacement );
message is unaffected by this method call.
This pattern /\{0\}/ works on online RegEx testers, but I feel I am
missing an important step porting it to java's Pattern class. I have
tried sticking /'s into the string, ending it with "g", etc. Nothing
seems to work. anyone have any insight into how I can do this or what
I am doing incorrectly?
TIA.
Jussi Piitulainen - 26 Mar 2008 15:16 GMT
> String message = "{0} should be 5 characters in length.";
> String replacement = "Zip Code";
> message.replaceAll( match, replacement );
>
> message is unaffected by this method call.
Strings are immutable. The method returns a new String.
message = message.replaceAll( match, replacement );
frosted74@gmail.com - 26 Mar 2008 15:26 GMT
On Mar 26, 10:16 am, Jussi Piitulainen <jpiit...@ling.helsinki.fi>
wrote:
> froste...@gmail.com writes:
> > String message = "{0} should be 5 characters in length.";
[quoted text clipped - 5 lines]
> Strings are immutable. The method returns a new String.
> message = message.replaceAll( match, replacement );
*Slaps self in forehead*. Thanks Jussi!!
Roedy Green - 26 Mar 2008 17:56 GMT
>I am trying to use a Pattern to match certain strings in error
>messages in our application. We are delimiting them using the
>following notation, {0}, {1}, etc. I am trying to use String's
>replaceFirst (even replaceAll) method to replace the instances of
>these tokens with appropriate Strings. I am using the following code:
you don't want a regex replace. You are just looking for an ordinary
string. "{0}"
so use String.replace to replace all, not String.replaceAll.

Signature
Roedy Green Canadian Mind Products
The Java Glossary
http://mindprod.com
Roedy Green - 26 Mar 2008 20:55 GMT
On Wed, 26 Mar 2008 16:56:55 GMT, Roedy Green
<see_website@mindprod.com.invalid> wrote, quoted or indirectly quoted
someone who said :
>so use String.replace to replace all, not String.replaceAll.
see http://mindprod.com/jgloss/string.html
for basic hints on using the class, including gotchas.

Signature
Roedy Green Canadian Mind Products
The Java Glossary
http://mindprod.com