正则表达式以匹配unicode块或索引范围

时间:2019-08-02 03:25:00

标签: php regex unicode pcre

我正在尝试创建一个正则表达式,以匹配unicode块中的任何字符,特别是Mathematical Alphanumeric Symbols块。

此处的目的是识别使用Unicode字符的内容的使用方式,以使其文本获得不同的格式,例如通常不支持的粗体或斜体文本。 like this one有很多网站可以帮助用户转换文本。

我尝试使用速记属性代码,但是它似乎无法与我希望从块中获得的所有字符匹配。

preg_match('/\p{Sm}/i', '?') === 1; // false

似乎PHP也不支持命名的变体,所以我无法做类似\p{Math}的事情。

我相信我需要针对块范围-从U + 1D400-U + 1D7FF,但是我无法弄清楚如何正确构建此正则表达式。这就是我以为我可以使用的方式,但是它似乎不起作用。

preg_match('/\x{1D400}-\x{1D7FF}/i', '?') === 1; // false

我希望这些字符都不匹配(直接在键盘上键入):

abcdefghijklmnopqrstuvwxyz0123456789

我希望这些字符中的每个字符都可以匹配(与上面相同,使用上面的链接转换为Math粗体):

????????????????????????????????????

1 个答案:

答案 0 :(得分:1)

我猜这个表达式可能有用,但是不确定:

$re = '/[\x{1D400}-\x{1D7FF}]+/su';
$str = '????????????????????????????????????';
preg_match_all($re, $str, $matches, PREG_SET_ORDER, 0);
var_dump($matches);

\p{S} or \p{Symbol}: math symbols, currency signs, dingbats, box-drawing characters, etc.
\p{Sm} or \p{Math_Symbol}: any mathematical symbol.
\p{Sc} or \p{Currency_Symbol}: any currency sign.
\p{Sk} or \p{Modifier_Symbol}: a combining character (mark) as a full character on its own.
\p{So} or \p{Other_Symbol}: various symbols that are not math symbols, currency signs, or combining characters.

该表达式在regex101.com的右上角进行了解释,如果您想探索/简化/修改它,在this link中,您可以观察到它如何与某些示例输入匹配,如果你喜欢。


参考

RegEx for Mathematical Alphanumeric Symbols

Unicode Regular Expressions