简体   繁体   English

使用正则表达式在Java中查找并替换字符串中的十六进制值

[英]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? 可以使用Java中的正则表达式来完成吗?

Yes, you can. 是的你可以。

This is a sample code to enclose the character sequences in range 0x3041 and 0x3096 by < and > . 这是一个示例代码,用<>将范围0x3041和0x3096中的字符序列括起来。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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