| 
                         使用星号 * 
- 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    
 
  
匹配所有字母和数字 
使用word 简写 
- const longHand = /[A-Za-z0-9_]+/;  
 - const shortHand = /w+/;  
 - const numbers = "42";  
 - const myFavoriteColor = "magenta";  
 - longHand.test(numbers); // true  
 - shortHand.test(numbers); // true  
 - longHand.test(myFavoriteColor); // true  
 - shortHand.test(myFavoriteColor); // true 
 
  
除了字母和数字,其他的都要匹配 
用W 表示 w 的反义 
- const noAlphaNumericCharRegex = /W/gi;  
 - const weirdCharacters = "!_$!!";  
 - const alphaNumericCharacters = "ab283AD";  
 - noAlphaNumericCharRegex.test(weirdCharacters); // true  
 - noAlphaNumericCharRegex.test(alphaNumericCharacters); // false 
 
  
匹配所有数字 
你可以使用字符集[0-9],或者使用简写 d 
- const digitsRegex = /d/g;  
 - const stringWithDigits = "My cat eats $20.00 worth of food a week.";  
 - stringWithDigits.match(digitsRegex); // ["2", "0", "0", "0"] 
 
  
匹配所有非数字 
用D 表示 d 的反义 
- const nonDigitsRegex = /D/g;  
 - const stringWithLetters = "101 degrees";  
 - stringWithLetters.match(nonDigitsRegex); // [" ", "d", "e", "g", "r", "e", "e", "s"] 
 
  
匹配空格                         (编辑:滁州站长网) 
【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! 
                     |