简体   繁体   中英

Find and replace hex values in a String in Java using regex

In one of the sections in my website, users can enter a long piece of text. User may enter some machine dependent characters which are not rendered correctly, so I want to perform a validation check before they save their information.

I have a range of hex values which are machine dependent and need to be avoided. I need to check their presence and highlight those characters.

One way to solve this is to read each characters in the string and compare it with the hex range and then replace it something to highlight. Can this be done using regex in Java?

Yes, you can.

This is a sample code to enclose the character sequences in range 0x3041 and 0x3096 by < and > .

    String s = "私は日本人です。";
    String r = s.replaceAll("[\u3041-\u3096]+", "<$0>");
    System.out.println(s);  // -> 私は日本人です。
    System.out.println(r);  // -> 私<は>日本人<です>。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM