1

I have a specific requirement to find a pattern and replace the value of matching group(2) in the original string by retaining the pattern(delimiter), I am using the pattern

:(\w+)[:\|]+(.*)

With this pattern it parse the values correctly but i am not able to replace the value of group(2). For example i have a multi-line input string

:20:9405601140
:2D::11298666
:28C:20/1

I want to replace the value(9405601140) of tag 20 with new value(1234) so the output i am expecting is

:20:1234
:2D::11298666
:28C:20/1

Thanks

4 Answers 4

1

Use this one:

input = input.replaceAll("(:20):(\\d+)(?!\\d)", "$1:1234");

Here (\\d+)(?!\\d) is checking whether the digits after the :20: are not followed by a digit or not.

However, if you want to replace only the :20:9405601140 there here it is much simple:

input = input.replaceAll(":20:9405601140(?!\\d)", ":20:1234");
Sign up to request clarification or add additional context in comments.

Comments

0

You can do this by capturing what you want to keep, instead of what you want to replace, and then using a backreference ($1, for the first capturing group) in the replacement string to include it in the final result.

Something like:

string.replaceAll("(:\\w+[:\\|]+).*", "$11234")

To perform the replacement on all the given lines, or just:

string.replaceAll("(:20[:\\|]+).*", "$11234")

To perform the replacement only on the line beginning with ":20".

2 Comments

Tag 20 may be repeating and the value(9405601140) can be part of other tags as well, i want to replace specific tag and specific occurrence value only, i have option to give occurrence to replace, so need to go by using find and as soon as i find the occurrence i have to replace it.
Not sure I'm following you. If you only need to replace the first instance, then use String.replaceFirst. If that's not what you are asking for, I'd need some clarification.
0

try this

s = s.replaceAll("\\A(?::[:\\|])\\w+", "1234");

Comments

0

How about doing it the other way around.

Create a pattern like this (:(\w+)[:\|]+)(.*) then for each row output the first group and your replacement (instead of group 2).

Here is an working example http://ideone.com/9TkGx6

1 Comment

This solutions works only if the tag value is in the same line, if tag value is mulit line like :20:123213\n45555\n67788 then it only replaces 123213 but the next two lines still stays...i tired using MULTILINE and DOTALL but does not work.

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.