Skip to content

正则常见表达式

正则匹配中文字符

支持unicode

参考地址

主流浏览器 js 引擎都支持 unicode

Unicode property escapes

js
const text = "你好,世界!";
// 使用正则表达式匹配中文字符
const chineseCharacters = text.match(/\p{Script=Han}+/gu);
if (chineseCharacters) {
  for (const chineseText of chineseCharacters) {
    console.log("匹配到的汉字字符: " + chineseText);
  }
} else {
  console.log("未找到汉字字符");
}
py
import re

# 匹配中文字符
pattern = re.compile(r'[\p{Han}]\w*', re.UNICODE)
text = '这是一个中文字符串'
match = pattern.search(text)
if match:
    print(match.group())  # 输出:这是一个中文字符串

不支持unicode

在较旧的引擎中,不完全支持 Unicode 属性的正则表达式,可以尝试使用 Unicode 范围 \u4e00-\u9fa5 来匹配汉字字符。

js
const text = "你好,世界!";
// 使用正则表达式匹配中文字符
const chineseCharacters = text.match(/[\u4e00-\u9fa5]+/g);
if (chineseCharacters) {
  for (const chineseText of chineseCharacters) {
    console.log("匹配到的汉字字符: " + chineseText);
  }
} else {
  console.log("未找到汉字字符");
}

Site developed by Aomd.