Delman Abdullah Delman Abdullah - 3 months ago 24
Java Question

Java replaceAll cannot replace a character in a string

I want to replace the Arabic Letter Heh (U+0647) to the Arabic Letter Ae (U+06D5) in a given string using Java

replaceAll(regex, replacement)
method. I have this code:

String arabicHeh = "\u0647‌"; // Arabic Letter Heh
String arabicAe = "\u06D5"; // Arabic Letter Ae

String text = txtPane.getText();
String newText = text.replaceAll(arabicHeh, arabicAe);


When I print
newText
variable nothing is changed, the letter
arabicHeh
is still exist in the string.

Note: The code works when I write it in this way:

String newText = text.replaceAll("ه", arabicAe);


In other words, the code works when I make the Arabic Letter Heh itself as a parameter to
replaceAll(regex, replacement)
, but I don't want to write the character
"ه"
itself inside my code because not all IDEs can read/show this character.

I think
arabibHeh
has problem, because also
text.contains(arabicHeh)
evaluates to
false
while it definitely contains
arabicHeh
, I thought may be the problem is in getting text from the
JTextPane
(
String text = txtPane.getText();
) but when I print
text
to console I get the same text as typed in the
JTextPane
, including the
arabicHeh
.

Anyone kindly can explain why
text.contains(arabicHeh)
evaluates to
false
or why the code is not working in
text.replaceAll(arabicHeh, arabicAe)
?

Answer

When I copypasted your snippet I've got space after \u0647‌

String arabicHeh = "\u0647‌ "; // Arabic Letter Heh

It is https://en.wikipedia.org/wiki/Zero-width_non-joiner

just remove it from your code snippet and all will work :)