JavaScript RegExp Meta 正则表达式元字符
正则表达式元字符
元字符是具有特殊含义的字符。
它们可以用来匹配数字、单词、空格等等:
// 匹配单词
const pattern = /\w/;JavaScript 正则表达式元字符
修订于 2025 年 7 月
| 元数据 | 描述 |
|---|---|
| \d | 匹配数字 |
| \D | 不匹配任何数字 |
| \w | 匹配字母数字单词字符 |
| \W | 不匹配任何字母数字单词字符 |
| \s | 匹配空格 |
| \S | 不匹配任何空格 |
| \ddd | 匹配八进制数字 ddd 的字符 |
| \xhh | 匹配十六进制数字 hh 的字符 |
| \uhhhh | 匹配十六进制数字 hhhh 的 Unicode 字符 |
正则表达式 \d(数字)元字符
元字符 \d 用于匹配数字。
示例
在字符串中全局搜索数字:
let text = "Give 100%!";
const pattern = /\d/g;
let result = text.match(pattern);
正则表达式 \D 元字符
\D 元字符匹配非数字字符。
示例
全局搜索非数字字符:
let text = "Give 100%!";
const pattern = /\D/g;
let result = text.match(pattern);亲自试一试 »正则表达式 \w(单词)元字符
\w 元字符匹配单词字符。
单词字符是指 a-z、A-Z、0-9 以及下划线 (_) 等字符。
示例
全局搜索单词字符:
let text = "Give 100%!";
const pattern = /\w/g;
let result = text.match(pattern);亲自试一试 »正则表达式 \W 元字符
\W 元字符匹配非单词字符。
单词字符是指 a-z、A-Z、0-9 以及下划线 (_) 等字符。
示例
全局搜索非单词字符:
let text = "Give 100%!";
const pattern = /\W/g;
let result = text.match(pattern);亲自试一试 »\s(空格)元字符
\s 元字符匹配空格、制表符和换行符等空白字符。
示例
字符串中空白字符的全局搜索:
let text = "Is this all there is?";
const pattern = /\s/g;
let result = text.match(pattern);
正则表达式 \xhh(十六进制)
\xhh 匹配十六进制数 hh 对应的字符。
字符串中十六进制字符 6F (o) 的全局替换:
let text = "Visit FreeW3C. Hello World!";
let pattern = /\x6F/g;
let result = text.replace(pattern, "*");亲自试一试 »正则表达式 \uhhhh(Unicode 十六进制)
\uhhhh 匹配十六进制代码为 hhhh 的 Unicode 字符。
示例
全局搜索十六进制代码为 0057 (W) 的 Unicode 字符:
let text = "Visit FreeW3C. Hello World!";
const pattern = /\u0057/g;
let result = text.match(pattern);
正则表达式方法
正则表达式的搜索和替换可以使用不同的方法。
以下是最常用的方法:
字符串方法
| 方法 | 描述 |
|---|---|
| match(regex) | 返回结果数组 |
| matchAll(regex) | 返回结果迭代器 |
| replace(regex) | 返回一个新的字符串 |
| replaceAll(regex) | 返回一个新的字符串 |
| search(regex) | 返回第一个匹配项的索引 |
| split(regex) | 返回一个结果数组 |
正则表达式方法
| 方法 | 描述 |
|---|---|
| regex.exec() | 返回结果迭代器 |
| regex.test() | 返回 true 或 false |
