Reputation: 242
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!
Upvotes: 0
Views: 2634
Reputation: 54692
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.
Upvotes: 0
Reputation: 15434
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");
Upvotes: 1
Reputation: 7854
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
Upvotes: 1
Reputation: 157457
At this purpose you can use String.format
int aInt = 12;
String.format("There are {%d} months in a year", aInt );
Upvotes: 4