正则表达式入门(六)匹配unicode和其他字符

时间:2023-03-09 17:49:25
正则表达式入门(六)匹配unicode和其他字符

匹配unicode字符
有时候我们需要匹配ASCII范围之外的字符。

"Qu’est-ce que la tolérance? c’est l’apanage de l’humanité. Nous sommes tous pétris de faiblesses et d’erreurs; pardonnons-nous réciproquement nos sottises, c’est la première loi de la nature." —Voltaire (1694–1778)

What is tolerance? It is the consequence of humanity. We are all formed of frailty and error;let us pardon reciprocally each other's folly--that is the first law of nature.

我们将伏尔泰的名言输入到http://www.regexpal.com/中,然后输入正则表达式

\u00e9

\u之后跟着的十六进制值00e9,这里不区分大小写,00E9也可以,00E9对接十进制值233,在ASCII(0~127)之外。

注意在Regexpal中字母é,即小写e加上了一个重音符,被标亮了,这是因为在unicode中é就是U+00E9,所以\u00e9可以匹配到它。

Regexpal.com是javascript的正则表达式实现。javascript也允许使用以下语法实现:

\xe9

现在我们在其他正则引擎中试一下。http://regexhero.net/tester/是.NET编写的。

古池
蛙飛び込む
水の音
—芭蕉 (1644–1694) At the ancient pond
a frog plunges into
the sound of water.
—Basho (1644–1694)

以上是日本诗人松尾芭蕉的俳句。
将其输入regexhero,然后输入正则

\u6c60

这是单词pond池塘所对应的日文字符的代码点。
另外,也可以匹配一下长破折号

\u2014

或短破折号

\u2013

用八进制数匹配字符
在正则中,用八进制数就是在反斜线后加三位数字。
比如

\351

等同于

\u00e9

匹配控制字符
代码库的ASCII.txt里是所有ASCII字符,一个字符一行,一共128行。
在正则表达式中,像这样来指定一个控制字符:

\cx

其中x就是你想匹配的控制字符
匹配unicode和其他字符

正则表达式入门(六)匹配unicode和其他字符