java.util.regex.PatternSyntaxException at String.matches

The java String.matches method checks the given string with the specified regular expression. If the string matches the regular expression, it will return true, otherwise it will return false. The exception java.util.regex.PatternSyntaxException is thrown, if the specified regular expression is invalid. 

The exception java.util.regex.PatternSyntaxException is thrown in the following methods in String class

  • String.matches
  • String.replaceFirst
  • String.replaceAll
  • String.split
Exception in thread "main" java.util.regex.PatternSyntaxException: Dangling meta character '*' near index 0
**
^
	at java.util.regex.Pattern.error(Pattern.java:1955)
	at java.util.regex.Pattern.sequence(Pattern.java:2123)
	at java.util.regex.Pattern.expr(Pattern.java:1996)
	at java.util.regex.Pattern.compile(Pattern.java:1696)
	at java.util.regex.Pattern.<init>(Pattern.java:1351)
	at java.util.regex.Pattern.compile(Pattern.java:1028)
	at java.util.regex.Pattern.matches(Pattern.java:1133)
	at java.lang.String.matches(String.java:2121)
	at com.yawintutor.StringMatches.main(StringMatches.java:9)

Root Cause

If invalid regular expression is provided in the java methods, then this exception will be thrown. validate the regular expression with the regular expression rules.

How to reproduce this issue

If you provide a invalid regular expression in the String.matches method, java can’t parse the regular expression string. So this exception will be thrown. In the example below, the String “**” is a invalid regular expression.

package com.yawintutor;

public class StringMatches {
	public static void main(String[] args) {
		String str = "Yawin";
		String str2 = "**";
		boolean index;

		index = str.matches(str2);

		System.out.println("Given String : " + str);
		System.out.println("String index : " + index);
	}
}

Solution

The String.matches method should be provided with a valid regular expression. the below example is shown with a valid regular expression. The more details about regular expression is available in java.util.regex.Pattern class.

package com.yawintutor;

public class StringMatches {
	public static void main(String[] args) {
		String str = "Yawin";
		String str2 = "Y.*";
		boolean index;

		index = str.matches(str2);

		System.out.println("Given String : " + str);
		System.out.println("String index : " + index);
	}
}

Output

Given String : Yawin
String index : true

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *