Regular expression to replace all but one character in a string

I need a regex to replace all matching characters except the first one squared in a string.

For instance:

To match with 'A' and replace with 'B'

  • "AAA" should be replaced by "ABB"

  • "AAA AAA" should be replaced by "ABB ABB"

To match with '' and replace with 'X'

  • '[space] [space] [space] A [space] [space] [space]' should be replaced by '[space] XXA [space] XX'
+4
source share
2 answers

You need to use this regex to replace:

\\BA

Working demo

  • \B ( ) , \B ( )
  • A A

Java:

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

UPDATE. :

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

:

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

2

+5

Lookbehind

(?<!^| )A :

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

.

  • (?<!^| ) , , , ,
  • A A

+4

Source: https://habr.com/ru/post/1546289/


All Articles