3

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.

4
  • What's the value of statement? Commented Dec 5, 2018 at 11:22
  • Try statement.replaceAll("length\\(([a-zA-Z]+)\\)", "LEN($1)"), see demo. Commented Dec 5, 2018 at 11:23
  • it will be a query as u can see from the test. (i.e. select length(x) from table y) Commented Dec 5, 2018 at 11:24
  • thanks - Wiktor solution worked! Commented Dec 5, 2018 at 11:28

1 Answer 1

3

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).

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.