Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular Expression to Replace All But One Character In String

Tags:

java

regex

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'
like image 272
Ammar Avatar asked Jan 11 '23 07:01

Ammar


1 Answers

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

like image 183
anubhava Avatar answered Jan 12 '23 21:01

anubhava