-5

What does the following code/regex do in Java. I am looking at code written by another dev, but I can't make what the following regex does? Besides is it a well-known regex-pattern to use circle and square brackets ?

str.replaceAll("([%_])", "\\$1");
robinCTS
  • 5,746
  • 14
  • 30
  • 37
ARK
  • 3,734
  • 3
  • 26
  • 29
  • 3
    Just replaces any `%` or `_` with a `$1` substring. Same as `.replace("%", "$1").replace("_", "$1")`. Perhaps, it was meant to be `str.replaceAll("([%_])", "\\\\$1");` so that `$1` could be parsed as a backreference, and then it would be escaping `%` and `_`. – Wiktor Stribiżew Feb 20 '18 at 18:10
  • The brackets and symbols have special meanings in regex. For instance `(` opens a capturing group and `[` a set of symbols. – Zabuzard Feb 20 '18 at 18:10
  • It matches a `%` or `_` character. This line of code will add a backslash to either one of those characters. It looks like you're preparing a String to go into an SQL `like` condition, where either of those characters would need to be escaped, due to their special meaning in SQL. – Dawood ibn Kareem Feb 20 '18 at 18:11
  • @DawoodibnKareem What does `$1` mean in SQL? How can we use `$1` for both `_` and `%` ? – ARK Feb 20 '18 at 18:24
  • `$1` doesn't mean anything special in SQL, but in the `replaceAll` method it means "the thing you found". So your line of Java replaces your `_` or `%` with "backslash followed by the thing you found". – Dawood ibn Kareem Feb 20 '18 at 18:28
  • @DawoodibnKareem Gotcha. So its bad code on the other dev's part. How would I replace `%` or `_` with `\%` or `\_` I want to replace those wildcards by adding backslash to it. – ARK Feb 20 '18 at 18:36
  • It's not bad code. It already does what you want. – Dawood ibn Kareem Feb 20 '18 at 19:09
  • I found the answer by @SebastienHelbert so short, precise, and to the point, that I thought that it deserved to have a question. – Andrey Tyukin Feb 21 '18 at 01:35

2 Answers2

1

The pattern just replaces any % or _ with a $1 substring and is the same as .replace("%", "$1").replace("_", "$1").

Perhaps, it was meant to be str.replaceAll("([%_])", "\\\\$1"); so that $1 could be parsed as a backreference, and then it would be escaping % and _.

See the Java demo:

System.out.println("% and _".replaceAll("([%_])", "\\$1"));    // => $1 and $1
System.out.println("% and _".replaceAll("([%_])", "\\\\$1"));  // => \% and \_
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
0

This code just escapes every '%' or '_' character by prefixing them with a backslash.

Andrey Tyukin
  • 43,673
  • 4
  • 57
  • 93
Sébastien Helbert
  • 2,185
  • 13
  • 22