简介:正则表达式表现为一种查寻模式,它帮助程序员去匹配、查寻、替换文本。
1.正则表达式的test方法来判断字符串是否匹配某个模式,使用方式为 regex.test(str) regex为一个正则表达式 str为你需要测试的字符串。如果字符串和该正则表达式匹配 则会返回true ,否则返回false
let testStr = "freeCodeCamp";
let testRegex = /Code/;
testRegex.test(testStr);
// 返回true
2.通过或操作符 | ,同时使用多个模式来匹配字符串
//如匹配'yes' 或 ‘no' 或 ‘maybe’
let testStr = "yes, I do";
let testRegex = /yes|no|maybe/;
testRegex.test(testStr);
// 返回true
//注:该匹配是从左到右直到发现匹配项 如果左边的选项匹配到了会忽略后面的匹配项
//例
'ab'.match(/a|ab/) =>['a'] 只能匹配到a
3.运用flag来匹配, g 进行全局匹配, 默认匹配到一次后就会停止,加了g之后会一直匹配直到字符串末尾;i 用来进行不区分大小写匹配,使用之后匹配时会忽略大小写;m进行多行匹配。
let testStr = "ignorecase Ignorecase";
let testRegex = /igNorecase/gi;
testRegex.test(testStr);
// 返回true
4.通过字符串match方法来获得匹配的结果,使用方法为 调用字符串的match方法并把正则表达式作为参数传给match.
let testStr = "Hello world!keep going!";
let testRegex = /hello|going/ig;
let result = testStr.match(testRegex);
// 返回['Hello', 'going']
5.使用通配符 . (一个点)来匹配任意字符 (不包括换行符\n 和回车符 \r)
let humStr = "I'll hum a song";
let hugStr = "Bear hug";
let huRegex = /hu./;
humStr.match(huRegex); // 返回 ["hum"]
hugStr.match(huRegex); // 返回 ["hug"]
6.使用方括号 [ ] 来匹配一类字符
let bigStr = "big", bugStr = 'bug',let bogStr = "bog";
let bgRegex = /b[aiu]g/;
bigStr.match(bgRegex); // Returns ["big"]
bugStr.match(bgRegex); // Returns ["bug"]
bogStr.match(bgRegex); // Returns null
7.使用连字符 - 来匹配某个范围的字母或数字
let catStr = "smallcat";
let numStr = 'zz56';
let bothStr = '139az';
let bgRegex = /[a-e]at/g;
let numRegex = /[1-5]/g;
let bothRegex = /[1-5a-z]/g;
catStr.match(bgRegex); // Returns ["cat"]
numStr.match(numRegex); // Returns ["5"]
bothString.match(bothRegex); //Returns ['1', '3', 'a', 'z']
8.通过 ^ 来匹配除了某些字符之外的字符。
//会匹配除了a e i o u 之外的所有字符, 注意 . ! [ @ / 还有空白符 也会匹配到
/[^aeiou]/gi
9. + 和 * 分别对应 至少出现一次和出现0次或多次
let difficultSpelling = "Mississippi";
let myRegex = /s+/g;
let otherRegex = /ig+/g;
difficultSpelling.match(myRegex);//returns ['ss', 'ss']
difficultSpelling.match(otherRegex);//returns null
let soccerWord = "gooooooooal!";
let gPhrase = "gut feeling";
let oPhrase = "over the moon";
let goRegex = /go*/;
soccerWord.match(goRegex); // Returns ["goooooooo"]
gPhrase.match(goRegex); // Returns ["g"]
oPhrase.match(goRegex); // Returns null
10. 正则中的贪婪匹配(尽可能多的去匹配)和懒匹配(尽可能少的去匹配),正则表达式默认是贪婪匹配, 在运算符后添加?使得运算符为非贪婪模式。
let text = "<h1>Winter is coming</h1>";
let myRegex = /<.*>/;
let otherRegex = /<.*?>/;
let result1 = text.match(myRegex); returns ["<h1>Winter is coming</h1>"]
let result2 = text.match(otherRegex); returns ['<h1>']
11.匹配以某个字符开头(^ 注:该符号放在[ ]里面表示除了之外的字符,详见第8点) 和 以某个字符结尾($)
let caboose = "The last car on a train is the caboose";
let lastRegex = /caboose$/;
let firstRegex= /^The/;
let result1 = lastRegex.test(caboose); returns true
let result2 = firstRegex.test(caboose); returns true
12. \w 匹配大小写字母、数字、下划线,等价于[A-Za-z0-9_];\W 除了大小写字母、数字、下划线之外的字符, 等价于[^A-Za-z0-9_];\d匹配0-9的数字, 等价于[0-9];\D匹配除了0-9的数字之外的字符, 等价于[^0-9]; \s匹配空白符,包括空格、tab、换页符、换行符 等价于[ \r\t\f\n\v]; \S匹配除了空白符之外的字符等价于[ ^\r\t\f\n\v]
//\w
let longHand = /[A-Za-z0-9_]+/;
let shortHand = /\w+/;
let numbers = "42";
let varNames = "important_var";
longHand.test(numbers); // Returns true
shortHand.test(numbers); // Returns true
longHand.test(varNames); // Returns true
shortHand.test(varNames); // Returns true
//\W
let shortHand = /\W/;
let numbers = "42%";
let sentence = "Coding!";
numbers.match(shortHand); // Returns ["%"]
sentence.match(shortHand); // Returns ["!"]
//\s
let whiteSpace = "Whitespace. Whitespace everywhere!"
let spaceRegex = /\s/g;
whiteSpace.match(spaceRegex);
// Returns [" ", " "]
//\W
let whiteSpace = "Whitespace. Whitespace everywhere!"
let nonSpaceRegex = /\S/g;
whiteSpace.match(nonSpaceRegex).length; // Returns 32
13. 限制匹配字符出现的次数上限和下限 ,或只限制下限 或限制具体次数
let A4 = "aaaah";
let A2 = "aah";
let multipleA = /a{3,5}h/;
multipleA.test(A4); // Returns true
multipleA.test(A2); // Returns false
//注 {3,}里面第二个数字不写同时保留逗号,表示只限制下限没有上限
//{3} 表示具体出现次数
14. 匹配模式中的的某个字符可能存在也可能不存在,通过问号 ? 来匹配。
let american = "color";
let british = "colour";
let rainbowRegex= /colou?r/;
rainbowRegex.test(american); // Returns true
rainbowRegex.test(british); // Returns true
15.向前匹配 分为包括的(?=...)和不包括的(?!...),包括的...内容必须存在但不会计入匹配的内容中,不包括的...内容不能存在。改模式常用来对字符串同时运用多个模式。
//3到6个字符中最少有一个数字
let password = "abc123";
let checkPass = /(?=\w{3,6})(?=\D*\d)/;
checkPass.test(password); // Returns true
16. replace简单使用及通过捕获组使用。replace方法接受两个参数,第一个可以是正则表达式也可以是字符串,第二个参数可以是你需要替换的内容,也可以是一个函数。
let wrongText = "The sky is silver.";
let silverRegex = /silver/;
wrongText.replace(silverRegex, "blue");
// Returns "The sky is blue."
"Code Camp".replace(/(\w+)\s(\w+)/, '$2 $1');
// Returns "Camp Code"
let str="hello world";
let str1=str.replace(/o/g,function(match,pos,orginText){
console.log(pos);
return "a";
});
console.log(str1);//hella warld
//replace方法第二个参数是函数时改函数拥有三个参数:
第一个参数是匹配到的字符串,第二个参数是匹配的位置,第三个参数是原字符串。
在函数里面可以对字符串进行操作。使用函数作为第二个参数,可以做一些复杂的替换,比如当匹配多个字符时候,可以对不同的字符做不同的替换。
17.反向引用。反向引用分组中捕获的内容,使用反斜线加上数字表示引用,该数字从1开始,第一个分组捕获的为\1,第二个为\2,以此类推。
例如正则表达式/^([dtn])a\1/,匹配的是:以字母d、t或n开头,其后连接字母a,再后连接第一个分组中捕获的内容。这种匹配规则与正则表达式/[dtn] a[dtn]/是不同的。a后面连接的字母不是任意的字母d、t或n,而必须与第一个分组中匹配到的字母完全相同。因此,\1匹配的具体字母是在运行时才能确定。
注:本内容主要整理自freeCodeCamp, 这个是github上排名第一的项目,一个免费的学习平台,由浅入深还不错,需要有一些英语基础。
也可查看这篇正则相关的文章教程
常用js正则表达式:
//匹配url query
let reg = /([^?=&]+)=([^?=&]*)/g;
let url = 'https://s.weibo.com/weibo?q=%236%E7%9C%81%E4%BB%BD%E6%9C%88%E6%9C%80%E4%BD%8E%E5%B7%A5%E8%B5%84%E6%A0%87%E5%87%86%E8%B6%852000%E5%85%83%23&Refer=top';
let newUrl = decodeURIComponent(url);
console.log(newUrl.match(reg)
//["q=#6省份月最低工资标准超2000元#", "Refer=top"]
let queryObj = {};
url.replace(reg, function(match, $1, $2, index, input) {
queryObj[$1] = $2;
})
//邮箱验证
let reg = /^([a-zA-Z]|[0-9])(\w|\-)+@[a-zA-Z0-9]+\.([a-zA-Z]{2,4})$/;
/*
*以数字或字母开头
*接着可以是多个字母、数字、下划线或 -
*然后是 @ 后面是多个数字、字母
*然后是 . 加 2到 4个字母结尾
*/
//查找字符串中出现最多的字符和个数
let str = "abcabcabcbbccccc",num = 0,char = '';
// 使其按照一定的次序排列
str = str.split('').sort().join('');
// "aaabbbbbcccccccc"
// 定义正则表达式
let re = /(\w)\1+/g;
str.replace(re, ($0, $1) => {
if (num < $0.length) {
num = $0.length;
char = $1;
}
});
console.log(`字符最多的是${char},出现了${num}次`);
//实现千位分隔符
parseToMoney(1234.56); // return '1,234.56'
parseToMoney(123456789); // return '123,456,789'
parseToMoney(1087654.321); // return '1,087,654.321'
function parseToMoney(num) {
num = parseFloat(num.toFixed(3));
let [integer, decimal] = String.prototype.split.call(num, '.');
integer = integer.replace(/\d(?=(\d{3})+$)/g, '$&,');
return integer + '.' + (decimal ? decimal : '');
}
let reg = /(?!^)(?=(\d{3})+$)/g;
str.replace(reg, ',')
//其中\b匹配的是位置,而不是任意字符,匹配的是单词的边界
const capitalizeEveryWord = str => str.replace(/\b[a-z]/g, char => char.toUpperCase());
//EXAMPLES
capitalizeEveryWord('hello world!'); // 'Hello World!'
//匹配img标签src内容
/<img.*?src=['"](.*?)['"]/gi