Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular Expressions with double backslash in java

Tags:

java

string

I want to understand the concept of regular expression in below code:

private static final String SQL_INSERT = "INSERT INTO ${table}(${keys}) 
VALUES(${values})";
private static final String TABLE_REGEX = "\\$\\{table\\}";
.
.
.
String query = SQL_INSERT.replaceFirst(TABLE_REGEX, "tableName");

The above code is working fine but i would like to understand how. As per my knowledge $ and { symbols should be escaped in java string using backslash but in above string there is no backslash and if I try to add it, it shows error: invalid escape sequence.

Also why the TABLE_REGEX = "\\$\\{table\\}"; contains double backslash?

like image 875
user812142 Avatar asked Aug 30 '26 22:08

user812142


1 Answers

The $ and { don't need to be escaped in Java string literals in general but in regular expressions they need to be escaped as they have special meaning in regular expressions. The $ matches the end of a line and { is used for matching characters a certain amount of times. To match any of the regular expression special characters themselves these characters need to be escaped. For example A{5} matches AAAAA but A\{5 matches A{5.

To escape something in a regular expression string you use the \. But the backslash in string literals itself needs escaping which is done by another \. That is the String literal "\\{" actually corresponds to the string "\{".

This is why in regular expression string literals you will often encounter multiple backslashes. You might also want to take a look at Pattern.quote(String s) which takes a string and properly escapes all special characters (wrt. Java regular expressions).

Essentially instead of

private static final String TABLE_REGEX = "\\$\\{table\\}";

you could write

private static final String TABLE_REGEX = Pattern.quote("${table}");

In your example SQL_INSERT.replaceFirst(TABLE_REGEX, "tableName"); matches the first occurrence of ${table} in SQL_INSERT and replaces this occurrence with tableName:

String sql = "INSERT INTO ${table}(${keys}) VALUES(${values})".replaceFirst("\\$\\{table\\}", "tableName");
boolean test = sql.equals("INSERT INTO tableName(${keys}) VALUES(${values})");
System.out.println(test); // will print 'true'
like image 65
dpr Avatar answered Sep 02 '26 06:09

dpr