0

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

5
  • Could you explain first among repeated characters in a string ? Commented Mar 24, 2016 at 10:39
  • @noob In the given example 'b' is a repeated character , i actually want to replace one of the occurence of 'b' Commented Mar 24, 2016 at 10:41
  • So you expected output is axcdexg ? Commented Mar 24, 2016 at 10:43
  • @noob No, expected output is either axcdebg or abcdexg Commented Mar 24, 2016 at 10:44
  • @sash check Evan Knowles answer Commented Mar 24, 2016 at 10:45

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for quick answer. I tried (.)(.*?\\1) and the replaceFirst still gives me wrong answer (same as mine): axg
Bro, sorry i tried replaceAll with x$2 and it looks like it works. Let me try with couple of inputs and i'll accept your answer. Thank you
0

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

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.