Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java regex matcher.replaceAll with groups

Tags:

java

regex

I'm trying to replace one syntax with another and i'm doing this through regex expressions where I would like to replace with one pattern with another.

Pattern pattern = Pattern.compile("length\\((?<field>[a-zA-Z]+)\\)", Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(statement);

if (matcher.find())
           statement = matcher.replaceAll("LEN(" + matcher.group("field") + ")");
        return statement;

It's a simple thing where I would like to replace all (loop through) the matches and replace them with another text. however i'm struggling with having the group iterate aswell dynamically.

Expected :select *,LEN(devise) lendevise,LEN(marche) lenmarche,LEN(nature) lennature from tableX where nseq='0'

Actual :select *,LEN(devise) lendevise,LEN(devise) lenmarche,LEN(devise) lennature from tableX where nseq='0'

So as u can notice here. the group value is always replaced by the group of the first match instead of the respective match which is being replaced?

Is there an efficient "best" way of doing this? I would like to avoid (if possible) to put the different groups in an separate arrays.

like image 293
MaximV Avatar asked Jul 26 '26 20:07

MaximV


1 Answers

I suggest simplifying the solution to a single replaceAll call, that will replace all matches inline and won't cause any trouble like the one you are having:

statement = statement.replaceAll("length\\(([a-zA-Z]+)\\)", "LEN($1)");

See the regex and Java demo.

String s = "select *,length(devise) lendevise,length(marche)  lenmarche,length(nature) lennature from tableX where nseq='0'";
System.out.println(s.replaceAll("length\\(([a-zA-Z]+)\\)", "LEN($1)"));
// => select *,LEN(devise) lendevise,LEN(marche) lenmarche,LEN(nature) lennature from tableX where nseq='0'

Note that ([a-zA-Z]+) forms a numbered capturing group whose value is later accessed by use of a $1 placeholder (or a replacement backreference).

like image 195
Wiktor Stribiżew Avatar answered Jul 29 '26 09:07

Wiktor Stribiżew



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!