Trying this will solve your issue.

str.replaceAll("\\p{Sc}", string_to_replcae);

and example can be like below:

String str = "For some reason my �double quotes� were lost.";
    str = str.replaceAll("\uFFFD", "\"");

this example can be viewed from here : How to replace � in a string

follow the link for more unicode expressions. http://www.regular-expressions.info/unicode.html

Answer from Raju Sharma on Stack Overflow
🌐
Baeldung
baeldung.com › home › java › java string › replace non-printable unicode characters in java
Replace Non-Printable Unicode Characters in Java | Baeldung
January 14, 2024 - @Test public void givenTextWithNonPrintableChars_whenUsingRegularExpression_thenGetSanitizedText() { String originalText = "\n\nWelcome \n\n\n\tto Baeldung!\n\t"; String expected = "Welcome to Baeldung!"; String regex = "[\\p{C}]"; Pattern pattern = Pattern.compile(regex); Matcher matcher = pattern.matcher(originalText); String sanitizedText = matcher.replaceAll(""); assertEquals(expected, sanitizedText); } In this test method, the regular expression \\p{C} represents any control characters (non-printable Unicode characters) in a given originalText.
Top answer
1 of 2
2

The correct way to do this is using a regex to match the entire unicode definition and use group-replacement.

The regex to match the unicode-string:

A unicode-character looks like \uABCD, so \u, followed by a 4-character hexnumber string. Matching these can be done using

\\u[A-Fa-f\d]{4}

But there's a problem with this:
In a String like "just some \\uabcd arbitrary text" the \u would still get matched. So we need to make sure the \u is preceeded by an even number of \s:

(?<!\\)(\\\\)*\\u[A-Fa-f\d]{4}

Now as an output, we want a backslash followed by the hexnum-part. This can be done by group-replacement, so let's get start by grouping characters:

(?<!\\)(\\\\)*(\\u)([A-Fa-f\d]{4})

As a replacement we want all backlashes from the group that matches two backslashes, followed by a backslash and the hexnum-part of the unicode-literal:

3

Now for the actual code:

String pattern = "(?<!\\\\)(\\\\\\\\)*(\\\\u)([A-Fa-f\\d]{4})";
String replace = "3";

Matcher match = Pattern.compile(pattern).matcher(test);
String result = match.replaceAll(replace);

That's a lot of backslashes! Well, there's an issue with java, regex and backslash: backslashes need to be escaped in java and regex. So "\\\\" as a pattern-string in java matches one \ as regex-matched character.

EDIT:
On actual strings, the characters need to be filtered out and be replaced by their integer-representation:

StringBuilder sb = new StringBuilder();
for(char c : in.toCharArray())
   if(c > 127)
       sb.append("\\").append(String.format("%04x", (int) c));
   else
       sb.append(c);

This assumes by "unicode-character" you mean non-ASCII-characters. This code will print any ASCII-character as is and output all other characters as backslash followed by their unicode-code. The definition "unicode-character" is rather vague though, as char in java always represents unicode-characters. This approach preserves any control-chars like "\n", "\r", etc., which is why I chose it over other definitions.

2 of 2
-4

Try using String.replaceAll() method

s = s.replaceAll("\u", "\");

Top answer
1 of 3
4

This is a character set issue. Make sure you read the file with the correct character set.

In character set Windows-1252, bytes C2 96 are characters  (U+00C2: Latin Capital Letter A with Circumflex) and (U+2013: En Dash).

In character set ISO 8859-1, byte 96 is undefined. Byte C2 is Â, same as for Windows-1252.

In character set UTF-8, bytes C2 96 is the encoding of Unicode code point U+0096 (<Start of Guarded Area> (SPA)).

In character set UTF-16BE, bytes C2 96 is the encoding of character (U+C296: not valid). In character set UTF-16LE, they would decode as character (U+96C2: Han Character).

The question code uses new String(byte[]), which uses the platform default character set, so it is unclear from the code alone which character set is being used.

Since it's running on Windows, and prints as –, it would appear to be using character set Windows-1252. As such, to replace the pair of characters that resulted from reading the file using that character set, use:

content.replace("\u00C2\u2013", "BadCharacter")

If the Java code had read the file using UTF-8, by calling new String(data, StandardCharsets.UTF_8), the code should be:

content.replace("\u0096", "BadCharacter")

FYI: UltraEdit likely opened the file using UTF-8, which is why it appeared to be an empty file. See "Unicode text and Unicode files in UltraEdit" to learn more about how UltraEdit handles Unicode files.

2 of 3
1

I am having trouble using Java to identify and replacing a specific character that appears in a text file I have. It is a non-printable character, but it seems that Java renders it as – when outputting to the console.

It seems to be this character: https://www.fileformat.info/info/unicode/char/c296/index.htm

I'll translate:

Joe said: "I have a square. It is a circle".

You've made conflicting statements. Is it a non-printable character, or is it 슖 which is perfectly printable (see? I just printed it), or is it something completely different, which shows up as 0xC2 96 in the file and you've immediately jumped to the conclusion that this must mean it is 슖 because that has unicode number 0xC296?

Before you call this a 'bad file', it's just an encoded file and you simply need to apply the proper encoding to it.

Whenever bytes turn into characters or vice versa, charset conversion is ALWAYS applied. You can't not do it. Thus, in new String(bytes), yup, charset conversion is applied. Which one? Well, the 'platform default', which is just a funny way of saying 'the wrong answer'. You never want playform default. Don't ever call new String(bytes), it's a dumb method you should never use.

Unfortunately, plain text files just do not have an encoding tagged along with the data. You can't read .txt files unless you already know what encoding you have. If you don't know, you can't read it, or, if you don't know but you have a pretty good idea of what's in the file, you can go into Sherlock Holmes mode and attempt to figure it out.

You've told java that it is encoded with 'platform default', whatever that might be, (looks like ISO-8859-1 or Win-1252), and you get garbage out, but that's because you specified the wrong encoding, not because 'java is bad' or 'the file is bad'. Just specify the right encoding and all is right as rain.

Open the file with a text editor of some renown (such as SublimeText, cot editor, notepad++, etc), and play around with the encoding value until the text makes sense.

You must use your human brain (this is pretty hard AI for a computer to do!) and look at the file and make an educated guess. For example, if I see Mç~ller in a file where it seems logical that these are last names of european origin, that probably said Müller, so now I can either try to backsolve (look up the hex sequence, and toss tha sequence + ü in a web search engine and that'll usually tell you what to do), or just keep picking encodings in my editor until I see Müller appear, and now I know.

Thus, if you've done that, and truly you ahve determined that 슖 makes sense, okay, backsolving for that, the only encoding that makes sense here is UTF-16BE. So, toss that in your editor, or use new String(thoseBytes, "UTF-16BE") and see if the stuff makes sense now.

In no case should you be doing what these other answers are suggesting which is that you read the file with the wrong encoding and then try to clean up the epic mess that results. That's a bit like that Mr Bean sketch for training to paint a house:

  1. Get a can of paint.
  2. Get a stick of dynamite.
  3. Put the can in the middle of the room.
  4. Light the dynamite.
  5. Put the dynamite in the can and all done!

... and then clean up the mess and fix all the areas the explosion didn't catch and put out the fire.

Or maybe just, ya know, skip the dynamite and just buy a paintroller instead.

Same here. Just decode those bytes the right way in the first place instead of scraping globs of paint and dynamite wrapper off the walls.

🌐
Java2s
java2s.com › ref › java › java-string-replace-whitespace-unicode-characters-with.html
Java String replace whitespace unicode characters with ' '
Java String replace whitespace unicode characters with ' ' Copy · //package com.demo2s; public class Main { public static void main(String[] argv) throws Exception { String str = "&^&^$^(&*demo2s.com"; System.out.println(collapseWhitespace(str)); }//from w ww .
🌐
Java2s
java2s.com › example › java › language-basics › string-replace-by-unicode.html
String replace by unicode - Java Language Basics
public class Main { private String jaText = "this is a test "; public Main() { String replaced = jaText.replaceFirst("\u6587\u5B57", "mojibake"); System.out.printf("Replaced: %s\n", replaced); }//from w w w.
🌐
CodingTechRoom
codingtechroom.com › question › replace-unicode-character-java-string
How to Replace a Unicode Character in a Java String - CodingTechRoom
The most common way is to utilize the String.replace() or String.replaceAll() methods, which allow you to specify the character or substring to be replaced and what you want it to be replaced with. ... String original = "Hello, \u2602!"; // Original string containing a Unicode character String ...
🌐
Stack Overflow
stackoverflow.com › questions › 47159873 › replace-unicode-characters
java - Replace unicode characters? - Stack Overflow
public class Localizer { String message; public Localizer(String message){ this.message=message; } public String Localize(){ message = message.replaceAll("\\u0103","&#259;").replaceAll("\\u00EE","&#238;").replaceAll("\\u0163","&#355;").replaceAll("\\u015F","&#351;").replaceAll("\\u00E2","&#226;").replaceAll("\\u00CE","&#206;").replaceAll("\\u0102","&#258;"); return message; } } ... Sign up to request clarification or add additional context in comments. ... Find the answer to your question by asking. Ask question ... See similar questions with these tags. ... This question is in a collective: a subcommunity defined by tags with relevant content and experts. ... 4 how to convert unicode \u003c to correct web content and display correct content in android webview so what i should do for that
Find elsewhere
🌐
Coderanch
coderanch.com › t › 372167 › java › Replacing-string
Replacing \\0020 in a string (Java in General forum at Coderanch)
Hi, I'm processing some strings where someone has typed in a unicode character by hand e.g. "hello\u0020there". In Java this is represented as "hello\\u0020there". What I want to do is replace the "\u0020" text with a " ". However, when I use: String s = "hello\u0020there"; s = s.replaceAll("\\u0020", " "); I don't get the expected "hello there", in fact it doesn't change at all.
🌐
How to do in Java
howtodoinjava.com › home › java regular expressions › java remove non-printable non-ascii characters using regex
Java remove non-printable non-ascii characters using regex
January 25, 2022 - Java program to clean string content from unwanted chars and non-printable chars. private static String cleanTextContent(String text) { // strips off all non-ASCII characters text = text.replaceAll("[^\\x00-\\x7F]", ""); // erases all the ASCII control characters text = text.replaceAll("[\\p{Cntrl}&&[^\r\n\t]]", ""); // removes non-printable characters from Unicode text = text.replaceAll("\\p{C}", ""); return text.trim(); } 2.1.
🌐
Oracle
docs.oracle.com › javase › tutorial › i18n › text › convertintro.html
Converting Non-Unicode Text (The Java™ Tutorials > Internationalization > Working with Text)
Because your program expects characters in Unicode, the text data it gets from the system must be converted into Unicode, and vice versa. Data in text files is automatically converted to Unicode when its encoding matches the default file encoding of the Java Virtual Machine.
🌐
Baeldung
baeldung.com › home › java › java string › remove accents and diacritics from a string in java
Remove Accents and Diacritics From a String in Java | Baeldung
January 8, 2024 - Second, we will remove all characters matching the Unicode Mark category using the \p{M} regex expression. We pick this category because it offers the broadest range of marks. Let’s start with some examples using core Java.
Top answer
1 of 2
10

Match the escape sequence \uXXXX with a regular expression. Then use a replacement loop to replace each occurrence of that escape sequence with the decoded value of the character.

Because Java string literals use \ to introduce escapes, the sequence \\ is used to represent \. Also, the Java regex syntax treats the sequence \u specially (to represent a Unicode escape). So the \ has to be escaped again, with an additonal \\. So, in the pattern, "\\\\u" really means, "match \u in the input."

To match the numeric portion, four hexadecimal characters, use the pattern \p{XDigit}, escaping the \ with an extra \. We want to easily extract the hex number as a group, so it is enclosed in parentheses to create a capturing group. Thus, "(\\p{XDigit}{4})" in the pattern means, "match 4 hexadecimal characters in the input, and capture them."

In a loop, we search for occurrences of the pattern, replacing each occurrence with the decoded character value. The character value is decoded by parsing the hexadecimal number. Integer.parseInt(m.group(1), 16) means, "parse the group captured in the previous match as a base-16 number." Then a replacement string is created with that character. The replacement string must be escaped, or quoted, in case it is $, which has special meaning in replacement text.

String data = "This is\\u2019 a sample text file \\u2014and it can ...";
Pattern p = Pattern.compile("\\\\u(\\p{XDigit}{4})");
Matcher m = p.matcher(data);
StringBuffer buf = new StringBuffer(data.length());
while (m.find()) {
  String ch = String.valueOf((char) Integer.parseInt(m.group(1), 16));
  m.appendReplacement(buf, Matcher.quoteReplacement(ch));
}
m.appendTail(buf);
System.out.println(buf);
2 of 2
7

If you can use another library, you can use apache commons https://commons.apache.org/proper/commons-text/javadocs/api-release/org/apache/commons/text/StringEscapeUtils.html

String dirtyString = "Colocaci\u00F3n";
String cleanString = StringEscapeUtils.unescapeJava(dirtyString);
//cleanString = "Colocación"
🌐
Baeldung
baeldung.com › home › java › java string › convert a string with unicode encoding to a string of letters
Convert a String with Unicode Encoding to a String of Letters | Baeldung
January 8, 2024 - In addition, we can use the Pattern and Matcher classes from the java.util.regex package to find all Unicode escape sequences in the input string. Then, we can replace each Unicode escape sequence:
🌐
Dirask
dirask.com › posts › Java-insert-unicode-character-to-string-1xy2bD
Java - insert unicode character to string
In this article, we would like to show you how to insert unicode character to string in Java. There are three different ways how to do it: with escape character...