Davide
Davide

Reputation: 2124

Regular expression replace characters by a given match between strings

I am trying to replace a given character by a regular expression match. For example, given the following string:
If you look at what you have in life, you'll always have more. If you look at what you don't have in life, you'll never have enough
I would like to replace all 't' with a '!' only where the match is between the characters 'ok' and 'fe'.

I get the match between 'ok' and 'fe' with this regular expression:

(?<=ok).*?(?=fe)

And I can only match one character with the following regex:

(?<=ok).*?(t).*?(?=fe)

I tried to transform that regex in the following way but it does not work:

(?<=ok).*?((t).*?)*?(?=fe)

How can I match all 't' between 'ok' and 'fe'? https://regex101.com/r/ORgseA/1

Upvotes: 3

Views: 109

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626903

You can use

String result = text.replaceAll("(?s)(\\G(?!\\A)|ok)((?:(?!ok|fe|t).)*)t(?=(?:(?!ok|fe).)*fe)", "$1$2!");

See the regex demo and the Java demo:

String text = "If you look at what you have in life, you'll always have more. If you look at what you don't have in life, you'll never have enough";
String result = text.replaceAll("(?s)(\\G(?!\\A)|ok)((?:(?!ok|fe|t).)*)t(?=(?:(?!ok|fe).)*fe)", "$1$2!");
System.out.println(result);
// => If you look a! wha! you have in life, you'll always have more. If you look a! wha! you don'! have in life, you'll never have enough

Details:

  • (?s) - Pattern.DOTALL embedded flag option (to make . match line break chars)
  • (\G(?!\A)|ok) - Group 1 ($1): ok or the end of the previous successful match
  • ((?:(?!ok|fe|t).)*) - Group 2 ($2): any one char, zero or more occurrences, as many as possible, that does not start a ok, fe or t char sequence
  • t - a t char
  • (?=(?:(?!ok|fe).)*fe) - immediately to the right, there must be any single char, zero or more occurrences, as many as possible, that does not start ok or fe char sequences and then a fe substring.

Upvotes: 3

Related Questions