G
grasp06110
Hi All,
I would like to hand the replaceAll() method of String text that it
would interpret as literal text and not as a regex. In the code I am
trying to implement I am given two variables and a string and need to
replace one variable with the second in the string. If either of the
variables contains a special character (e.g. $) the replaceAll() method
can fail. An example of this is shown below. In the example below I
can escape the $ character with /$ but I don't want to have to search
each string for every potential trouble maker. I would like to tell
the regex to treat the entire string as a literal.
Any help would be appreciated.
Thanks,
John
public class Ouch {
public static void main(String[] args) throws Exception {
String start = "yours now for just <amount>";
String price = "$9.99";
String end = start.replaceAll("<amount>", price);
System.out.println(end);
}
}
Exception in thread "main" java.lang.IndexOutOfBoundsException: No
group 9
at java.util.regex.Matcher.group(Matcher.java:463)
at java.util.regex.Matcher.appendReplacement(Matcher.java:730)
at java.util.regex.Matcher.replaceAll(Matcher.java:806)
at java.lang.String.replaceAll(String.java:2000)
at Ouch.main(Ouch.java:7)
I would like to hand the replaceAll() method of String text that it
would interpret as literal text and not as a regex. In the code I am
trying to implement I am given two variables and a string and need to
replace one variable with the second in the string. If either of the
variables contains a special character (e.g. $) the replaceAll() method
can fail. An example of this is shown below. In the example below I
can escape the $ character with /$ but I don't want to have to search
each string for every potential trouble maker. I would like to tell
the regex to treat the entire string as a literal.
Any help would be appreciated.
Thanks,
John
public class Ouch {
public static void main(String[] args) throws Exception {
String start = "yours now for just <amount>";
String price = "$9.99";
String end = start.replaceAll("<amount>", price);
System.out.println(end);
}
}
Exception in thread "main" java.lang.IndexOutOfBoundsException: No
group 9
at java.util.regex.Matcher.group(Matcher.java:463)
at java.util.regex.Matcher.appendReplacement(Matcher.java:730)
at java.util.regex.Matcher.replaceAll(Matcher.java:806)
at java.lang.String.replaceAll(String.java:2000)
at Ouch.main(Ouch.java:7)