Showing posts with label metacharacter. Show all posts
Showing posts with label metacharacter. Show all posts

Wednesday, June 3, 2009

JAVA: PatternSyntaxException: Dangling meta character '*' near index

Pattern Syntax Exception is thrown when you have "*" in any String and you want to replace "*" with something else.
This exception is likely when you use method java.lang.String.replaceAll().

There are two solutions to this problem.
Solution 1: escape all metacharacters and use replaceAll().

Solution 2:
I prefer this solution over solution 1. This method reduces most of the work as you don't need to escape any metacharacters.
Just use org.apache.commons.lang.StringUtils

Thursday, April 9, 2009

JAVA: illegal group reference

How:
You have a string "I like dollar symbol".
and you want to replace the string with "I like $ symbol".
Code:

String a = "I like dollar symbol"
String replacement = "$"
a = a.replaceAll("dollar", replacement);


This will throw an exception "Illegal group reference."

java.lang.IllegalArgumentException: Illegal group reference
at java.util.regex.Matcher.appendReplacement(Matcher.java:713)
at java.util.regex.Matcher.replaceAll(Matcher.java:813)
at java.lang.String.replaceAll(String.java:2190)


Solution:
Here the problem is "$" is a Metacharacter which should be escaped.

  • replacement = Matcher.quoteReplacement(replacement);
    a = a.replaceAll("dollar", replacement);


    About quoteReplacement method in Matcher class
    Ref. link: Click here
    Returns a literal replacement String for the specified String. This method produces a String that will work use as a literal replacement s in the appendReplacement method of the Matcher class. The String produced will match the sequence of characters in s treated as a literal sequence. Slashes ('\') and dollar signs ('$') will be given no special meaning.

  • put two backslashes before "$".

    String replacement = "\\$"