I am having problem with android regex pattern.
My target is to find {#} inside one sentence and replaces them with an array of String.
For example, my raw string will be
{#} students go to {#}.
My replacement array will be
[“5″,”park”]
After replacing, final string should be “5 students go to park.” My current snippet work just fine until the replacement array comes up with $ sign such as
[“$5″,”$park”]
Here is my current snippet.
Pattern pattern = Pattern.compile("(\\{#\\})");
String raw_q = "Pete has {#}. He bought {#}.";
String[] var = ["$70","6 pens at $5 each"];
String act_q = "";
for (int m = 0; m < var.length(); m++) {
try{
act_q = raw_q.replaceFirst(pattern.pattern(),var[m]);
}catch(Exception e){
e.printStackTrace();
}
Result is a blank string which I believe try block never get executed. Stack trace shows arrayindexoutofbound exception. I don’t really get what it’s happening. Any help would be appreciated.
Note – the length of replacement array is always equal to the number of {#} occurrences.
For your problem, see the javadoc.
String.replaceFirst()useMatcher.replaceFirst(), which refers toMatcher.appendReplacement():That is, you must escape all
$and\.But you have other problem…. You have compile a pattern and NOT use it!
replaceFirst()always compile the pattern again. Try this for better performance.