正则速查 - kscarrot/blog GitHub Wiki

文档

MDN Regular expression

regexone

js Info

名词

数字 \d 空白符 \s 字母和数字 \w 单词边界 \b

名词

(expression1)|(expression2) 逻辑或 |代表匹配expression1 或者 expression2

gra|ey 等同于 gra 或 ey

方括号(集合名词Collective noun) 可以作为字符类逻辑或的简写

gr(a|e)y 等同于 gr[ae]y

方括号也可以包含 字符范围

例如,[a-z] 表示从 a 到 z 范围内的字符,[0-5] 表示从 0 到 5 的数字。

从这里引申出一些简写符号

\d 等同于 [0-9] \w 等同于 [a-zA-Z0-9_] \s 等同于 [\t\n\v\f\r ]

可以用^修饰一下 变成否定的语义

[^abc] 匹配 chop中的 h

量词

确切数量 {n}

范围数量 {n,m}

可以上略上限 {n,} 匹配大于等于n个数量

常用缩写

+ => {1,} 一次或多次 ? => {0,1} 0次或一次 * => {0,} 0次或多次

捕获组

一个正则表达式模式使用括号,将导致相应的子匹配被记住

"John Smith".match(/(\w+)\s(\w+)/)
/** out put
['John Smith', 'John', 'Smith', index: 0, input: 'John Smith', groups: undefined]
*/

索引0代表最近一个匹配到的字符串 索引0+代表所有被记住的字符串

str.replace(re, "$2, $1");
/** output 
Smith, John
*/

在字符串相关方法可以被快捷的引用参考文档

用可嵌套的圆括号可以捕获 使用 (?<命名>) 可以命名

命名括号

let dateRegexp = /(?<year>[0-9]{4})-(?<month>[0-9]{2})-(?<day>[0-9]{2})/;
let str = "2019-04-30";

let groups = str.match(dateRegexp).groups

/** out put
{
    "year": "2019",
    "month": "04",
    "day": "30"
}
*/


str.replace(dateRegexp, "$<month>/$<day> $<year>")
/** out put
'04/30 2019'
*/

第二个参数传函数的例子

let dateString = "Today is 2023-05-15, tomorrow is 2023-05-16.";
// 使用命名捕获组的正则表达式
let dateRegex = /(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/g;


let newDateString = dateString.replace(dateRegex, (...props) => {
	// match, p1, p2, /* …, */ pN, offset, string, groups
	const groups = props.at(-1);
	return `${groups.month}-${groups.day}-${groups.year}`;
});

用例搜集

⚠️ **GitHub.com Fallback** ⚠️