1

how can i find the last visible character in a Java String? I'd like to remove all line breaks and other invisible characters from a Java String

Kind Regards, Tord

sunyata
  • 1,843
  • 5
  • 27
  • 41

2 Answers2

13
string_variable.replaceAll("\\p{C}", "?");

This will replace all non-printable characters. Where p{C} selects the invisible control characters and unused code points.

  • Thank you for your help, unfortunately this will remove all characters, i'm trying to find the last visible character in an article (like maybe a period or a letter or a number). Then i can remove the rest of the characters that are coming after that – sunyata Sep 20 '15 at 22:49
4

You can use the trim() method of the String class for removing trailing (and leading) white space and line breaks:

String trimmed = original.trim();
Mick Mnemonic
  • 7,808
  • 2
  • 26
  • 30
  • trim does not remove '\u200B' (zero width space). which is the problem I was having. Using .replaceAll("\\p{C}", "?") from the more upvoted answer worked for me – Cumulo Nimbus Sep 21 '22 at 23:14