4

I need regular expression to replace all matching characters except the first one in a squence in string.

For example;

For matching with 'A' and replacing with 'B'

  • 'AAA' should be replaced with 'ABB'

  • 'AAA AAA' should be replaced with 'ABB ABB'

For matching with ' ' and replacing with 'X'

  • '[space][space][space]A[space][space][space]' should be replaced with '[space]XXA[space]XX'
2
  • The first character of the string, or the first matching character? Commented Jun 27, 2014 at 11:03
  • @jcaron Yes the first matching character in a sequence Commented Jun 27, 2014 at 11:05

2 Answers 2

5

You need to use this regex for replacement:

\\BA

Working Demo

  • \B (between word characters) assert position where \b (word boundary) doesn't match
  • A matches the character A literally

Java Code:

String repl = input.replaceAll("\\BA", "B");

UPDATE For second part of your question use this regex for replacement:

"(?<!^|\\w) "

Code:

String repl = input.replaceAll("(?<!^|\\w) ", "X");

Demo 2

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

9 Comments

It's working fine for most of cases except for spaces. Any suggestion?
Give me a sample value for which it doesn't work and I will tweak it.
' ABC ' should be replaced with ' --ABC --' that appears to be totally new requirement. Can you clarify it?
It's not working for multiple spaces in a sequence, when space it to be replaced with some other character.
Actually I added 3 spaces before and after 'ABC' in the mentioned example, but editor replaced all with one space.
|
4

Negative Lookbehind and Beginning of String Anchor

Use the regex (?<!^| )A like this:

String resultString = subjectString.replaceAll("(?<!^| )A", "B");

In the demo, inspect the substitutions at the bottom.

Explanation

  • (?<!^| ) asserts that what immediately precedes the position is neither the beginning of the string nor a space character
  • A matches A

Reference

4 Comments

FYI, added explanation and demo. :)
I edited the regex, demo and explanation, Ammar, please have a look. :)
@AvinashRaj Yes, that would have worked too. But I really like to treat lookbehinds as "a real person", you know what I mean? Give it some meat, like for this C# regex we had earlier.
Ammar, if you want to have more rules, for instance it can happen after several spaces... You just keep changing the simple lookbehind, and adding ORs if needed. For instance, (?<!^|[ ]*) if you can have multiple spaces before the first A, and (?<!^|[ ]*|[@_]) if you also don't want to replace the first A after a @ or _... It's a very very flexible method, you can keep expanding it.

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.