需要字串比對、搜尋等等功能時,regex 正規表示式非常好用。以下是一份 regex 的備忘單,方便需要時可以翻閱。

  • 原文出處:https://dev.to/emmabostian/regex-cheat-sheet-2j2a

測試正規表示式

  • 使用 .test() 方法
let testString = "My test string";
let testRegex = /string/;
testRegex.test(testString);

測試多種模式

  • 使用 OR 運算子 (|)
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"]

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

  • 定義一組您希望匹配的字元
  • 放在中括號內即可[]
// Match "cat" "fat" and "mat" but not "bat"
const regexWithCharClass = /[cfm]at/g;
const testString = "cat fat bat mat";
const allMatchingWords = testString.match(regexWithCharClass); // ["cat", "fat", "mat"]

匹配字母表中的字母

  • 使用字元集合 [a-z]
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

匹配結尾字串

  • 在正則表達式末尾使用美元符號 $ 來檢查字串末尾是否匹配
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

匹配所有字母和數字

  • 使用 \w 簡寫
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"]

匹配字元數

  • 您可以使用 {lowerBound, upperBound} 在一行中指定特定數量的字元
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

匹配最少的字元數

  • 您可以使用 {lowerBound,} 要求滿足最少數量的字元
  • 這稱為數量說明符
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

某字元可以不出現

  • 要允許某字元可以不出現,請使用 ?
const britishSpelling = "colour";
const americanSpelling = "Color";
const languageRegex = /colou?r/i;

languageRegex.test(britishSpelling); // true
languageRegex.test(americanSpelling); // true

以上是基礎用法&範例,方便工作時可以查閱!


共有 0 則留言