22

I have a URI that contains non-ASCII characters like :

http://www.abc.de/qq/qq.ww?MIval=typo3_bsl_int_Smtliste&p_smtbez=Schmalbl�ttrigeSomerzischeruchtanb

How can I remove "�" from this URI

1
  • 2
    The set of possible characters is large compared to the set of characters allowed in the query part of a URI. To delete all non-English text would exclude many languages. Is this what you want? Or do you want to percent-encode the text? Or do you want to transliterate the text to English?
    – McDowell
    May 13, 2012 at 18:57

5 Answers 5

41

I'm guessing that the source of the URL is more at fault. Perhaps you're fixing the wrong problem? Removing "strange" characters from a URI might give it an entirely different meaning.

With that said, you may be able to remove all of the non-ASCII characters with a simple string replacement:

String fixed = original.replaceAll("[^\\x20-\\x7e]", "");

Or you can extend that to all non-four-byte-UTF-8 characters if that doesn't cover the "�" character:

String fixed = original.replaceAll("[^\\u0000-\\uFFFF]", "");
3
  • is \u0000 - \uFFFF 4 bytes? or 2 bytes.
    – JSixface
    Mar 27, 2019 at 20:07
  • @JSixface: a Unicode character in Java is 16 bits, or 2 bytes. But, in the context of the ranges specified within this regex string, that question doesn't make sense to me.
    – Cᴏʀʏ
    Mar 28, 2019 at 0:59
  • [^\x00-\x7F] is the correct range for ascii chars, if you put x20 as starting range you will remove also new line chars. Aug 20, 2019 at 9:46
21
yourstring=yourstring.replaceAll("[^\\p{ASCII}]", "");
7

No no no no no, this is not ASCII ... [^\x20-\x7E]

This is real ascii: [^\x00-\x7F]

Otherwise it will trim out newlines and other special characters that are part of ascii table!

1
  • Thank you! I was wondering where my newlines went!! May 28, 2021 at 15:37
6

To remove the Non- ASCII characters from String, below code worked for me.

String str="<UPC>616043287409ÂÂÂÂ</UPC>";

str = str.replaceAll("[^\\p{ASCII}]", "");

Output:

<UPC>616043287409</UPC>
1
  • 1
    Please try to avoid just dumping code as an answer and try to explain what it does and why. Your code might not be obvious for people who do not have the relevant coding experience.
    – Frits
    Aug 8, 2016 at 14:36
4

Use Guava CharMatcher

String onlyAscii = CharMatcher.ascii().retainFrom(original)
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.