Use the Repalceall method to appear java.util.regex.PatternSyntaxException:Dangling meta character ' * ' near index 0 exception
The code is as follows:
1 @Test 2 Public void Testreplaceall () {3 String sql = "SELECT * from Per_handle where ID not in (' 3ce7405509414105a65e7456987e7393 ')"; 4 String countsql = Sql.replaceall ("*", "count (*)"); 5 6 System.out.println (countsql); 7 }
The following error was reported after running in JUnit test mode:
java.util.regex.PatternSyntaxException:Dangling Meta character ' * ' near index 0
This error is related to the Repalceall method, and the ReplaceAll method structure can be seen in the Java API documentation as follows:
String Java.lang.String.replaceAll (string regex, string replacement)
Replaces this string with the given replacement for all substrings that match the given regular expression.
The first argument is a regular expression, and the second argument is the replaced string.
Because "*" has a special meaning in regular expressions, it results in an error.
Two workarounds are attempted:
1, the "*" to escape processing, so that it becomes a normal character
1 @Test 2 Public void Testreplaceall () {3 String sql = "SELECT * from Per_handle where ID not in (' 3ce7405509414105a65e7456987e7393 ')"; 4 String countsql = Sql.replaceall ("\\*", "Count (*)"); 5 System.out.println (countsql); 6 }
2. Replace ReplaceAll method with replace method
1 @Test 2 Public void Testreplaceall () {3 String sql = "SELECT * from Per_handle where ID not in (' 3ce7405509414105a65e7456987e7393 ')"; 4 String countsql = Sql.replace ("*", "count (*)"); 5 System.out.println (countsql); 6 }
The reasons for this approach to success are:
String Java.lang.String.replace (charsequence target, charsequence replacement)
The first argument of the Replace method is a character or string, so "*" is treated as a normal string by default.
Java.util.regex.PatternSyntaxException:Dangling Meta character ' * ' near index 0