javascript中的utf-8字边界正则表达式 [英] utf-8 word boundary regex in javascript

查看:170
本文介绍了javascript中的utf-8字边界正则表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在JavaScript中:

In JavaScript:

"ab abc cab ab ab".replace(/\bab\b/g, "AB");

正确地给了我:

"AB abc cab AB AB"

当我使用utf-8字符时虽然:

When I use utf-8 characters though:

"αβ αβγ γαβ αβ αβ".replace(/\bαβ\b/g, "AB");

字边界算子似乎不起作用:

"αβ αβγ γαβ αβ αβ"

有解决方案吗?

推荐答案

单词边界断言仅匹配单词字符前面或后面跟不是另一个单词字符(所以 .\b。等于 \ W\w \ w\W )。 \w 定义为 [A-Za-z0-9 _] 。所以 \w 与希腊字符不匹配。因此,对于这种情况,你不能使用 \b

The word boundary assertion does only match if a word character is not preceded or followed by another word character (so .\b. is equal to \W\w and \w\W). And \w is defined as [A-Za-z0-9_]. So \w doesn’t match greek characters. And thus you cannot use \b for this case.

你可以做的是使用它:

What you could do instead is to use this:

"αβ αβγ γαβ αβ αβ".replace(/(^|\s)αβ(?=\s|$)/g, "$1AB")

这篇关于javascript中的utf-8字边界正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆