使用星号 *
- const zeroOrMoreOsRegex = /hi*/gi;
- const normalHi = "hi";
- const happyHi = "hiiiiii";
- const twoHis = "hiihii";
- const bye = "bye";
- normalHi.match(zeroOrMoreOsRegex); // ["hi"]
- happyHi.match(zeroOrMoreOsRegex); // ["hiiiiii"]
- twoHis.match(zeroOrMoreOsRegex); // ["hii", "hii"]
- bye.match(zeroOrMoreOsRegex); // null
惰性匹配
- 字符串中与给定要求匹配的最小部分
- 默认情况下,正则表达式是贪婪的(匹配满足给定要求的字符串的最长部分)
- 使用 ? 阻止贪婪模式(惰性匹配 )
- const testString = "catastrophe";
- const greedyRexex = /c[a-z]*t/gi;
- const lazyRegex = /c[a-z]*?t/gi;
- testString.match(greedyRexex); // ["catast"]
- testString.match(lazyRegex); // ["cat"]
匹配起始字符串模式
要测试字符串开头的字符匹配,请使用插入符号^,但要放大开头,不要放到字符集中
- const emmaAtFrontOfString = "Emma likes cats a lot.";
- const emmaNotAtFrontOfString = "The cats Emma likes are fluffy.";
- const startingStringRegex = /^Emma/;
- startingStringRegex.test(emmaAtFrontOfString); // true
- startingStringRegex.test(emmaNotAtFrontOfString); // false
匹配结束字符串模式
使用 $ 来判断字符串是否是以规定的字符结尾
- const emmaAtBackOfString = "The cats do not like Emma";
- const emmaNotAtBackOfString = "Emma loves the cats";
- const startingStringRegex = /Emma$/;
- startingStringRegex.test(emmaAtBackOfString); // true
- startingStringRegex.test(emmaNotAtBackOfString); // false
匹配所有字母和数字 (编辑:西安站长网)
【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!
|