JS常用正則表達式備忘錄

摘要: 玩轉正則表達式。

Fundebug經授權轉載,版權歸原作者所有。

正則表達式或“regex”用於匹配字符串的各個部分 下面是我創建正則表達式的備忘單。

匹配正則

使用 .test() 方法

let testString = "My test string";
let testRegex = /string/;
testRegex.test(testString);

匹配多個模式

使用操作符號 |

const regex = /yes|no|maybe/;    

忽略大小寫

使用i標誌表示忽略大小寫

const caseInsensitiveRegex = /ignore case/i;
const testString = 'We use the i flag to iGnOrE CasE';
caseInsensitiveRegex.test(testString); // true

提取變量的第一個匹配項

使用 .match() 方法

const match = "Hello World!".match(/hello/i); // "Hello"

提取數組中的所有匹配項

使用 g 標誌

const testString = "Repeat repeat rePeAT";
const regexWithAllMatches = /Repeat/gi;
testString.match(regexWithAllMatches); // ["Repeat", "repeat", "rePeAT"]   

匹配任意字符

使用通配符. 作爲任何字符的佔位符

// To match "cat", "BAT", "fAT", "mat"
const regexWithWildcard = /.at/gi;
const testString = "cat BAT cupcake fAT mat dog";
const allMatchingWords = testString.match(regexWithWildcard); // ["cat", "BAT", "fAT", "mat"]    

用多種可能性匹配單個字符

  • 使用字符類,你可以使用它來定義要匹配的一組字符
  • 把它們放在方括號裏 []
//匹配 "cat" "fat" and "mat" 但不匹配 "bat"
const regexWithCharClass = /[cfm]at/g;
const testString = "cat fat bat mat";
const allMatchingWords = testString.match(regexWithCharClass); // ["cat", "fat", "mat"]    

匹配字母表中的字母

使用字符集內的範圍 [a-z]

const regexWidthCharRange = /[a-e]at/;

const regexWithCharRange = /[a-e]at/;
const catString = "cat";
const batString = "bat";
const fatString = "fat";

regexWithCharRange.test(catString); // true
regexWithCharRange.test(batString); // true
regexWithCharRange.test(fatString); // false

匹配特定的數字和字母

你還可以使用連字符來匹配數字

const regexWithLetterAndNumberRange = /[a-z0-9]/ig;
const testString = "Emma19382";
testString.match(regexWithLetterAndNumberRange) // true

匹配單個未知字符

要匹配您不想擁有的一組字符,使用否定字符集 ^

const allCharsNotVowels = /[^aeiou]/gi;
const allCharsNotVowelsOrNumbers = /[^aeiou0-9]/gi;

匹配一行中出現一次或多次的字符

使用 + 標誌

const oneOrMoreAsRegex = /a+/gi;
const oneOrMoreSsRegex = /s+/gi;
const cityInFlorida = "Tallahassee";

cityInFlorida.match(oneOrMoreAsRegex); // ['a', 'a', 'a'];
cityInFlorida.match(oneOrMoreSsRegex); // ['ss'];   

匹配連續出現零次或多次的字符

使用星號 *

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    

代碼部署後可能存在的BUG沒法實時知道,事後爲了解決這些BUG,花了大量的時間進行log 調試,這邊順便給大家推薦一個好用的BUG監控工具 Fundebug

匹配結束字符串模式

使用 $ 來判斷字符串是否是以規定的字符結尾

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"]

匹配空格

使用 \s 來匹配空格和回車符

const sentenceWithWhitespace = "I like cats!"
var spaceRegex = /\s/g;
whiteSpace.match(sentenceWithWhitespace); // [" ", " "]

匹配非空格

\S 表示 \s 的反義

const sentenceWithWhitespace = "C a t"
const nonWhiteSpaceRegex = /\S/g;
sentenceWithWhitespace.match(nonWhiteSpaceRegex); // ["C", "a", "t"]

匹配的字符數

你可以使用 {下界,上界} 指定一行中的特定字符數

const regularHi = "hi";
const mediocreHi = "hiii";
const superExcitedHey = "heeeeyyyyy!!!";
const excitedRegex = /hi{1,4}/;

excitedRegex.test(regularHi); // true
excitedRegex.test(mediocreHi); // true
excitedRegex.test(superExcitedHey); //false

匹配最低個數的字符數

使用{下界, }定義最少數量的字符要求,下面示例表示字母 i 至少要出現2次

const regularHi = "hi";
const mediocreHi = "hiii";
const superExcitedHey = "heeeeyyyyy!!!";
const excitedRegex = /hi{2,}/;

excitedRegex.test(regularHi); // false
excitedRegex.test(mediocreHi); // true
excitedRegex.test(superExcitedHey); //false

匹配精確的字符數

使用{requiredCount}指定字符要求的確切數量

const regularHi = "hi";
const bestHi = "hii";
const mediocreHi = "hiii";
const excitedRegex = /hi{2}/;

excitedRegex.test(regularHi); // false
excitedRegex.test(bestHi); // true
excitedRegex.test(mediocreHi); //false  

匹配0次或1次

使用 ? 匹配字符 0 次或1次

const britishSpelling = "colour";
const americanSpelling = "Color";
const languageRegex = /colou?r/i;

languageRegex.test(britishSpelling); // true
languageRegex.test(americanSpelling); // true
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章