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

5.5k Views Asked by At

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?

1

There are 1 best solutions below

2
On BEST ANSWER

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);  // -> 私<は>日本人<です>。