RaceBase
RaceBase

Reputation: 18848

Java String Regex replacement

Sample Input:

a:b
a.in:b
asds.sdsd:b
a:b___a.sds:bc___ab:bd

Sample Output:

a:replaced
a.in:replaced
asds.sdsd:replaced
a:replaced___a.sds:replaced___ab:replaced

String which comes after : should be replaced with custom function. I have done the same without Regex. I feel it can be replaced with regex as we are trying to extract string out of specific pattern.

For first three cases, it's simple enough to extract String after :, but I couldn't find a way to deal with third case, unless I split the string ___ and apply the approach for first type of pattern and again concatenate them.

Upvotes: 2

Views: 63

Answers (2)

Avinash Raj
Avinash Raj

Reputation: 174696

Just replace only the letters with exists next to : with the string replaced.

string.replaceAll("(?<=:)[A-Za-z]+", "replaced");

DEMO

or

If you also want to deal with digits, then add \d inside the char class.

string.replaceAll("(?<=:)[A-Za-z\\d]+", "replaced");

Upvotes: 4

vks
vks

Reputation: 67968

(:)[a-zA-Z]+

You can simply do this with string.replaceAll.Replace by $1replaced.See demo.

https://regex101.com/r/fX3oF6/18

Upvotes: 4

Related Questions