Pruthvi Raj Nadimpalli
Pruthvi Raj Nadimpalli

Reputation: 1373

Java regex replace repeated characters (including non consequent)

I'm trying to write a regular expression to replace first among repeated characters in a string.

The catch is the repeated characters can also be non-consequent.

    Ex: 

    Input: abcdebg
    Replace by character:  x
    Expected Output: axcdebg

I have been trying to do this with a regular expression: (.).*(\\1) But the result when i do a replace is: axg

Please suggest how i can achieve the expected result.

Thanks,
Sash

Upvotes: 0

Views: 87

Answers (2)

anubhava
anubhava

Reputation: 786359

You can use this lookahead based regex to replace a character only if same character is found ahead in input:

String str = "abcdebg";
String repl = str.replaceFirst("(.)(?=.*\\1)", "x");
//=> axcdebg

Upvotes: 0

Evan Knowles
Evan Knowles

Reputation: 7511

The problem here is that you're matching the rest of the string up until the repeated character as well, which means it's also being replaced. You'll need to capture it and include it again.

So,

regex: (.)(.*?\\1)

Replace with (for x): x\2

Upvotes: 2

Related Questions