Pramod
Pramod

Reputation: 129

Java regex replace the group value in original string

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

Upvotes: 1

Views: 1346

Answers (4)

Sabuj Hassan
Sabuj Hassan

Reputation: 39355

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");

Upvotes: 1

Andreas Wederbrand
Andreas Wederbrand

Reputation: 39951

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

Upvotes: 0

Evgeniy Dorofeev
Evgeniy Dorofeev

Reputation: 135992

try this

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

Upvotes: 0

femtoRgon
femtoRgon

Reputation: 33341

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

Upvotes: 0

Related Questions