2

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.

2 Answers 2

4

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");
Sign up to request clarification or add additional context in comments.

5 Comments

just to update, :bc___ can be something like this :b566 or :4545. I guess we should consider numbers too
then add \\d inside the char class.
sorry for not clarifying. It can contain any data :[email protected] or :b@_g+.com .But guranteed not to contain : and ____ as these are self-defined pattern
could be dump question now, how do I call custom function instead of directly replacing with "replaced". My custom function should get the matching string matcher.group()
ask this as a new question. I think you need to include the replaceAll function within while function.
4
(:)[a-zA-Z]+

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

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

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.