← 中文资源

简体中文版本

CANON_EQ 规范等价匹配重音

不加 CANON_EQ 时预组合 é 匹配不到 e 加组合符的分解形态,加上 CANON_EQ 后正则按规范等价比较,两种写法互相命中,搜索用户输入时很关键。

阅读英文原文

实现说明

CANON_EQ 规范等价匹配重音以类 AccentMatcher和函数 main为骨架。

使用要点

  • 演示输出是带标签的(plain matches decomposed:、canonical matches decomposed:、plain matches precomposed:),每个操作都会留下自己的一行标注。

常见问题

运行「CANON_EQ 规范等价匹配重音」会打印什么?

整个文件跑完,输出行以 plain matches decomposed:、canonical matches decomposed:、plain matches precomposed: 这类前缀开头。

核心语句

String decomposed = "cafe\u0301"; // e + combining acute: 分解形态的 accents
String precomposed = "caf\u00e9"; // 预组合 é
// 缺省时 plain regex 匹配不到分解形态;CANON_EQ 按规范等价比较
Pattern plain = Pattern.compile(precomposed);
Pattern canonical = Pattern.compile(precomposed, Pattern.CANON_EQ);

代码示例

import java.util.regex.Pattern;

public class AccentMatcher {

    public static void main(String[] args) {
        String decomposed = "cafe\u0301"; // e + combining acute: 分解形态的 accents
        String precomposed = "caf\u00e9"; // 预组合 é

        // 缺省时 plain regex 匹配不到分解形态;CANON_EQ 按规范等价比较
        Pattern plain = Pattern.compile(precomposed);
        Pattern canonical = Pattern.compile(precomposed, Pattern.CANON_EQ);

        System.out.println("plain matches decomposed: " + plain.matcher(decomposed).find());
        System.out.println("canonical matches decomposed: " + canonical.matcher(decomposed).find());
        System.out.println("plain matches precomposed: " + plain.matcher(precomposed).find());
    }
}