介绍
小编给大家分享一下JS常用正则表达式是什么,相信大部分人都还不怎么了解,因此分享这篇文章给大家参考一下,希望大家阅读完这篇文章后大有收获、下面让我们一起去了解一下吧!
匹配正则
使用<代码> test() 代码>方法
让testString=拔也馐詓tring"; 让testRegex=/字符串; testRegex.test (testString);
匹配多个模式
使用操作符号<代码> | 代码>
const regex=/是的没有| |也许;
忽略大小写
使用<代码>我> 代码标志表示忽略大小写
const caseInsensitiveRegex=//我忽略大小写; const testString=& # 39;我们使用我旗忽视案例# 39;; caseInsensitiveRegex.test (testString);//真正的
提取变量的第一个匹配项
使用<代码> .match() 代码>方法
const testString=爸馗粗馗磖ePeAT"; const regexWithAllMatches=/重复/胃肠道; testString.match (regexWithAllMatches);//(“Repeat",“Repeat",“Repeat"]
匹配任意字符
使用通配符<代码>。> 代码作为任何字符的占位符
//匹配“cat",“BAT",“fAT",“mat" const regexWithWildcard=//gi必备; const testString=懊鸬案庵镜鎑og"; const allMatchingWords=testString.match (regexWithWildcard);//(“cat",“BAT",“fAT",“mat"]
用多种可能性匹配单个字符
- <李>使用字符类,你可以使用它来定义要匹配的一组字符李> <李>把它们放在方括号里<代码>[]代码> 李>
//匹配“cat"“fat"和“;mat"但不匹配“bat" const regexWithCharClass=//g (cfm); const testString=懊ㄅ烛餸at"; const allMatchingWords=testString.match (regexWithCharClass);//(“cat",“fat",“mat"]
匹配字母表中的字母
使用字符集内的范围<代码> [a - z] 代码>
const regexWidthCharRange=/(a e)/; const regexWithCharRange=/(a e)/; const catString=癱at"; const batString=癰at"; const fatString=癴at"; regexWithCharRange.test (catString);//正确的 regexWithCharRange.test (batString);//正确的 regexWithCharRange.test (fatString);//错误
匹配特定的数字和字母
你还可以使用连字符来匹配数字
匹配单个未知字符
要匹配您不想拥有的一组字符,使用否定字符集,<代码> ^ 代码>
const allCharsNotVowels=/[^五个母音字母)/胃肠道; const allCharsNotVowelsOrNumbers=/[^ aeiou0-9]/gi;匹配一行中出现一次或多次的字符
使用<代码> +> 代码标志
const> const zeroOrMoreOsRegex=/嗨*/胃肠道; const normalHi=癶i"; const happyHi=癶iiiiii"; const twoHis=癶iihii"; const再见=癰ye"; normalHi.match (zeroOrMoreOsRegex);//(“hi") happyHi.match (zeroOrMoreOsRegex);//(“hiiiiii") twoHis.match (zeroOrMoreOsRegex);//(“hii",“hii"] bye.match (zeroOrMoreOsRegex);//空惰性匹配
- <李>字符串中与给定要求匹配的最小部分李> <李>默认情况下,正则表达式是贪婪的(匹配满足给定要求的字符串的最长部分)李> <李>
使用<代码> ?代码>阻止贪婪模式(惰性匹配)
李>const testString=癱atastrophe"; const greedyRexex=t/c [a - z] */胃肠道; const lazyRegex=/c [a - z] * ? t/胃肠道; testString.match (greedyRexex);//(“catast") testString.match (lazyRegex);//(“cat")
匹配起始字符串模式
要测试字符串开头的字符匹配,请使用插入符号<代码> ^> 代码,但要放大开的头,不要放到字符集中
const emmaAtFrontOfString=鞍晗不陡删蛔约旱拿ê芏?; const emmaNotAtFrontOfString=懊ò晗不睹兹椎?”; const startingStringRegex=^艾玛/; startingStringRegex.test (emmaAtFrontOfString);//正确的 startingStringRegex.test (emmaNotAtFrontOfString);//错误JS常用正则表达式是什么