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

JS常用正则表达式备忘录

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

使用星号 *

  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    

匹配所有字母和数字

(编辑:西安站长网)

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

热点阅读