正则示例
正则示例
温度
1
/^[-+]?[0-9]+(\.[0-9]*)?$/;
IPV4 地址
1
/^(([01]?\d\d?|2[0-4]\d|25[0-5])\.){3}([01]?\d\d?|2[0-4]\d|25[0-5])$/;
匹配浮点数
1
/-?([0-9]+(\.[0-9]*)?|\.[0-9]+)/;
校验 HTTP URL
1
/^https?://([^/:]+)(:(\d+))?(/.*)?$/i
重复检查
1
2
/^(.+)\1+$/.test("abcdabcdabcdabcd");
// output: true
Match
单词分隔
1
2
"this is a good idea".match(/\w+/g);
// output: ['this', 'is', 'a', 'good', 'idea']
处理文件路径
1
2
"/usr/local/cc.bin".match(/^(.*)\/([^/]*)$/);
// output: ['/usr/local/cc.bin', '/usr/local', 'cc.bin'
字符插入
1
2
3
4
5
6
7
8
"Toms and Jacks dot run!".replace(/(?<=\b\w+)(?=s\b)/g, "'");
// output: Tom's and Jack's dot run!
"1234567".replace(/(?<=\d)(?=(\d{3})+$)/g, ",");
// output: 1,234,567
"total: 1234567 dollors".replace(/(?<=\d)(?=(\d\d\d)+(?!\d))/g, ",");
// output: total: 1,234,567 dollors
捕获双引号内的内容
1
2
3
'this is "good" or "bad" idea'.match(/("[^"]*")/g);
'this is "good" or "bad" idea'.match(/(".*?")/g);
// output: ["good", "bad"]
HTML 捕获某个标签内的内容
1
2
"this is <b>good</b> or <b>bad</b> idea".match(/<b>((?!<b>).)*?<\/b>/g);
// output: ['<b>good</b>', '<b>bad</b>']
去除首位空格
1
2
3
4
5
const trim = (str) => {
str = str.replace(/^\s+/, "");
str = str.replace(/\s+$/, "");
return str;
};
This post is licensed under
CC BY 4.0
by the author.