You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用\p{InLatin1Supplement}正则报错?Unicode块匹配问题咨询

Java正则\p{InLatin1Supplement}报错原因及解决办法

问题出在你混淆了Java常量名和Unicode块的标准字符串名称。

Java正则的\p{InXxx}语法中,Xxx必须是UnicodeBlock.forName()能直接识别的标准块名称,而不是Character.UnicodeBlock的常量名。Character.UnicodeBlock.LATIN_1_SUPPLEMENT这个常量对应的标准块名称是"Latin-1 Supplement"(包含连字符和空格),而不是你写的Latin1Supplement——你把常量名里的下划线直接去掉的写法不符合要求,UnicodeBlock.forName("Latin1Supplement")实际上会抛出异常,自然正则解析会失败。

正确的写法有三种:

  • 直接使用标准块名:\p{InLatin-1 Supplement}
  • 使用block关键字指定:\p{block=Latin-1 Supplement} 或 \p{blk=Latin-1 Supplement}
  • 直接用Latin-1 Supplement对应的字符范围(U+0080到U+00FF):[\u0080-\u00FF]

代码示例

import java.util.regex.Pattern;

public class Latin1SupplementRegexTest {
    public static void main(String[] args) {
        // 验证正确写法
        Pattern validPattern1 = Pattern.compile("\\p{InLatin-1 Supplement}");
        Pattern validPattern2 = Pattern.compile("\\p{block=Latin-1 Supplement}");
        Pattern validPattern3 = Pattern.compile("[\\u0080-\\u00FF]");

        // 测试匹配©(属于Latin-1 Supplement的字符)
        String testChar = "©";
        System.out.println(validPattern1.matches(".*\\p{InLatin-1 Supplement}.*", testChar)); // true
        System.out.println(validPattern2.matches(".*\\p{block=Latin-1 Supplement}.*", testChar)); // true
        System.out.println(validPattern3.matches(".*[\\u0080-\\u00FF].*", testChar)); // true
    }
}

内容的提问来源于stack exchange,提问作者xtay2

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.29 22:33:14