Ammar
Ammar

Reputation: 1821

Regular Expression to Replace All But One Character In String

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'

For matching with ' ' and replacing with 'X'

Upvotes: 4

Views: 3788

Answers (2)

anubhava
anubhava

Reputation: 785286

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

Upvotes: 5

zx81
zx81

Reputation: 41838

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

Upvotes: 4

Related Questions