0

I'm working on Android and I want to replace all ocurrences of a certain {character} in a String with another String. For example, if the character we're talking about is 'a'and the replacement is "12" then:

Input : There are {a} months in a year.
Output : There are 12 months in a year.

I don't know how to deal with the replaceAll method and regexes ...

Thank you!

1
  • Did you try it? Did you search for examples of replaceAll usage? Commented Dec 4, 2012 at 8:18

4 Answers 4

4

At this purpose you can use String.format

int aInt = 12;
String.format("There are {%d} months in a year",  aInt );
Sign up to request clarification or add additional context in comments.

Comments

1

you can use string.replace("{a}", "12") it replaces all occurrences of {a} by 12 in a string and doesnt take regular expression. If you need to search patterns then use replaceAll

Comments

1

As you don't need use regex here, vishal_aim's answer is better for this situation.

The first attempt with replaceAll would be

String str = "There are {a} months in a year.";
str.replaceAll("{a}", "12");  

but it doesn't work because replaceAll takes a regex and {} are special characters in regex so you need to escape them:

str.replaceAll("\\{a\\}", "12");

5 Comments

Thanks that is what I was Looking for .. I actually tried it this way but I thought escaping would be with one slash only, and it did not compile!!
Next time please add it to a question. It will be obvious what you tried.
but why do you need to use replaceAll instead of replace?
@vishal_aim yes, using replace makes more sense. Thank you.
it seems to me that replace only works for one char and I need to replace a String "{a}" ...
0
String str = "There are {a} months in a year.";

str.replaceAll(Pattern.quote("{a}"), "12");

EDIT:

java.util.regex.Pattern.quote(String) methods returns a literal pattern String for the specified String.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.