0

I need help in regular expression using in regex java.

I need change group in string:

Example:

Input:

=sum($var1;2) or =if($result<10;"little";"big") ...

Need Output:

=sum(teste;2) or =if(teste<10;"little";"big") ...

Code I have:

Pattern p = Pattern.compile("(\\.*)(\\$\\w)(\\.*)");
Matcher m = p.matcher(total);
if (m.find()) {
    System.out.println(m.replaceAll("$2teste"));
}

Output I have:

=sum($vtestear1;2)
=if($r testeesultado<5;"maior";"menor")
1
  • Pattern.compile("([$]\\w+)") and m.replaceAll("teste") Commented Jun 14, 2013 at 11:14

1 Answer 1

1

Why match everything when all you need is to match variable tokens?

Pattern p = Pattern.compile("\\b\\$[a-z0-9]+\\b");
p.matcher(total).replaceAll("teste");

Change the [a-z0-9] part if you can have more than lowercase ASCII letters and digits.

Also, you don't need to test for .find() or anything if you .replace(): no match means nothing will be replaced.

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.