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?
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'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With