0

I am trying to replace certain values from a string using java regex

for example the string looks like

:20:1234
    6789
:28G::xyz
|20:3456
    1234
|29C:pqr
:20|9876 

I want to replace tag 20 value (may be multi line value) for second occurrence

|20:3456
    1234

with new value(may be multi line value) 6789 so the final replacement string i am expecting is

:20:1234
    6789
:28G::xyz
|20:6789
|29C:pqr
:20|9876 
3
  • 2
    I don't understand your question, but it seems that my answer to your question about a half-hour ago, contains concepts that will also help you here. Commented Mar 23, 2014 at 4:54
  • Why does the |29C:pqr change to ::29C:pqr? Commented Mar 23, 2014 at 5:02
  • It was typo corrected it now, thxs Commented Mar 23, 2014 at 5:07

2 Answers 2

0

Try this regex:

String str = ":20:1234\n    6789\n:28G::xyz\n|20:3456\n    1234\n|29C:pqr\n:20|9876 \n|20:3456\n    :20:1234\n";
str = str.replaceAll("(\\|20:)[\\s\\S]*?(?=[|:])","$1" + "6789\n");

Here it is checking until it reaches to anything other than | or :, so that it doesn't pick all.

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

Comments

0

This should work (tested):

str.replaceAll("(\\|" + "20" + ":)[^|:]*\n","$1" + "6789" + "\n");

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.