Reputation: 1821
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'
Upvotes: 4
Views: 3788
Reputation: 785286
You need to use this regex for replacement:
\\BA
\B
(between word characters) assert position where \b
(word boundary) doesn't matchA
matches the character A
literallyJava 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");
Upvotes: 5
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 characterA
matches A
Reference
Upvotes: 4