gpt4 book ai didi

java - 当第一个字符与任何其他字符一起使用时,正则表达式出错

转载 作者:行者123 更新时间:2023-12-02 00:37:05 25 4
gpt4 key购买 nike

对于我正在做的项目,我必须读取字符串。该字符串可能包含一个或多个 unicode 字符的十六进制表示形式(例如,“\u0161”代表“š”)。我想将这些代码转换为正确的字符表示形式。

为此,我首先需要检测字符串中是否存在格式为“\uAAAA”的十六进制序列,因此我编写了以下正则表达式:

Pattern classPattern = Pattern.compile("\\u[0-9a-fA-F]{4}");
Matcher classMatcher = classPattern.matcher("\\u1ECD");
System.out.println(classMatcher.find());

不幸的是,这会生成“java.util.regex.PatternSyntaxException:索引 2 附近的非法 Unicode 转义序列”错误。

但是,如果我仅出于测试目的而将“\”替换为“@”,则正则表达式将按预期工作:

Pattern classPattern = Pattern.compile("@u[0-9a-fA-F]{4}");
Matcher classMatcher = classPattern.matcher("@u1ECD");
System.out.println(classMatcher.find());

这让我相信我的反斜杠做错了。我还尝试了许多其他序列,但没有一个起作用。请帮忙。

最佳答案

“\u”在 Java 正则表达式世界中具有特殊含义,即匹配实际的 unicode 字符。 您必须对 \ 进行双重转义才能获得匹配你渴望。

Pattern classPattern = Pattern.compile("\\\\u[0-9a-fA-F]{4}");

[更新]正如评论所指出的,我给出正确答案的推理是有缺陷的。

关于java - 当第一个字符与任何其他字符一起使用时,正则表达式出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7514493/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com