Question about java.util.regex.Pattern

F

frosted74

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.
 
J

Jussi Piitulainen

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 );
 
R

Roedy Green

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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,579
Members
45,053
Latest member
BrodieSola

Latest Threads

Top