加入收藏 | 设为首页 | 会员中心 | 我要投稿 核心网 (https://www.hxwgxz.com/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 建站 > 正文

JS常用正则表达式备忘录

发布时间:2019-04-30 15:49:54 所属栏目:建站 来源:前端小智
导读:正则表达式或regex用于匹配字符串的各个部分 下面是我创建正则表达式的备忘单。 匹配正则 使用 .test() 方法 lettestString=Myteststring; lettestRegex=/string/; testRegex.test(testString); 匹配多个模式 使用操作符号 | constregex=/yes|no|maybe/;

使用星号 *

  1. const zeroOrMoreOsRegex = /hi*/gi;  
  2. const normalHi = "hi";  
  3. const happyHi = "hiiiiii";  
  4. const twoHis = "hiihii";  
  5. const bye = "bye";  
  6. normalHi.match(zeroOrMoreOsRegex); // ["hi"]  
  7. happyHi.match(zeroOrMoreOsRegex); // ["hiiiiii"]  
  8. twoHis.match(zeroOrMoreOsRegex); // ["hii", "hii"]  
  9. bye.match(zeroOrMoreOsRegex); // null 

惰性匹配

  •     字符串中与给定要求匹配的最小部分
  •     默认情况下,正则表达式是贪婪的(匹配满足给定要求的字符串的最长部分)
  •     使用 ? 阻止贪婪模式(惰性匹配 ) 
  1. const testString = "catastrophe";  
  2.  const greedyRexex = /c[a-z]*t/gi;  
  3.  const lazyRegex = /c[a-z]*?t/gi;  
  4.  testString.match(greedyRexex); // ["catast"]  
  5.  testString.match(lazyRegex); // ["cat"]    

匹配起始字符串模式

要测试字符串开头的字符匹配,请使用插入符号^,但要放大开头,不要放到字符集中

  1. const emmaAtFrontOfString = "Emma likes cats a lot.";  
  2. const emmaNotAtFrontOfString = "The cats Emma likes are fluffy.";  
  3. const startingStringRegex = /^Emma/;  
  4. startingStringRegex.test(emmaAtFrontOfString); // true  
  5. startingStringRegex.test(emmaNotAtFrontOfString); // false    

匹配结束字符串模式

使用 $ 来判断字符串是否是以规定的字符结尾

  1. const emmaAtBackOfString = "The cats do not like Emma";  
  2. const emmaNotAtBackOfString = "Emma loves the cats";  
  3. const startingStringRegex = /Emma$/;  
  4. startingStringRegex.test(emmaAtBackOfString); // true  
  5. startingStringRegex.test(emmaNotAtBackOfString); // false    

匹配所有字母和数字

使用word 简写

  1. const longHand = /[A-Za-z0-9_]+/;  
  2. const shortHand = /w+/;  
  3. const numbers = "42";  
  4. const myFavoriteColor = "magenta";  
  5. longHand.test(numbers); // true  
  6. shortHand.test(numbers); // true  
  7. longHand.test(myFavoriteColor); // true  
  8. shortHand.test(myFavoriteColor); // true 

除了字母和数字,其他的都要匹配

用W 表示 w 的反义

  1. const noAlphaNumericCharRegex = /W/gi;  
  2. const weirdCharacters = "!_$!!";  
  3. const alphaNumericCharacters = "ab283AD";  
  4. noAlphaNumericCharRegex.test(weirdCharacters); // true  
  5. noAlphaNumericCharRegex.test(alphaNumericCharacters); // false 

匹配所有数字

你可以使用字符集[0-9],或者使用简写 d

  1. const digitsRegex = /d/g;  
  2. const stringWithDigits = "My cat eats $20.00 worth of food a week.";  
  3. stringWithDigits.match(digitsRegex); // ["2", "0", "0", "0"] 

匹配所有非数字

用D 表示 d 的反义

  1. const nonDigitsRegex = /D/g;  
  2. const stringWithLetters = "101 degrees";  
  3. stringWithLetters.match(nonDigitsRegex); // [" ", "d", "e", "g", "r", "e", "e", "s"] 

匹配空格

(编辑:核心网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

热点阅读