0

I have a string in Java like this:

REF([123],[456],[78]),REF([789],[456],[12]),{111},REF([8069],[8098],[56])

I need to remove all the third occurring digits inside all the REFs. Meaning I need to remove [78], [12] and [56] (starting from the second comma till before the closing brackets) from the string so that I get this following output:

REF([123],[456]),REF([789],[456]),{111},REF([8069],[8098])

What should my regex be?

2
  • Could there ever be four numbers in a REF, and if so, what should happen then? Commented Jan 10, 2014 at 9:48
  • There can not be a fourth number inside REF, Tim. Also REF could also exists as "ref" or "Ref", being case insensitive. Commented Jan 10, 2014 at 10:09

1 Answer 1

3
String result = subject.replaceAll(
    "(?xi)(      # Match and capture in group 1:\n" +
    "REF\\(      # REF(\n" +
    "\\[\\d+\\], # a number in brackets, comma,\n" +
    "\\[\\d+\\]  # a number in brackets\n" +
    ")           # End of capturing group\n" +
    ",\\[\\d+\\] # Match a comma and a third number in brackets", "$1");
Sign up to request clarification or add additional context in comments.

2 Comments

Love the comments mode, haven't seen that before.
This is a precise and elegant solution. Beautifully explained as well. Thank you very much Tim.

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.