Javascrip 正则表达式速查表

F2E 前端

正则表达式 「regex」 ,用于在一个字符串中匹配部分内容。下面是我整理出来的创建和使用正则表达式速查表。


测试正则表达式

  • 使用 .test() 方法
    let testString = "My test string"; // 声明字符串变量
    let testRegex = /string/;  //声明正则表达式变量,这种形式代表是 regex
    testRegex.test(testString); //由于含 "string" ,返回 true

测试多模式中任意一个存在

  • 使用 操作符 (|
const regex = /yes|no|maybe/;

忽略大小写

  • 使用 i 开关标志表示大小写不敏感
const caseInsensitiveRegex = /ignore case/i; //注意最后的 i
const testString = 'We use the i flag to iGnOrE CasE';
caseInsensitiveRegex.test(testString); // 由于字符串中的 "iGnOrE CasE" 在忽略大小写的情况下与 “ignore case” 相同,故命中返回 true

从字符串中抽出第一个匹配项

  • 使用 .match() 函数
const match = "Hello World!".match(/hello/i); // 常量 match = "Hello"

从字符串中抽出所有匹配项到一个数组中

  • 使用 g 开关标志
const testString = "Repeat repeat rePeAT";
const regexWithAllMatches = /Repeat/gi; //最后的 g 表示全部。
testString.match(regexWithAllMatches); // 返回 ["Repeat", "repeat", "rePeAT"]

匹配任意的一个字符

  • 使用通配符 . 表示一个字符的占位,可匹配任何字符
// 匹配 "cat", "BAT", "fAT", "mat" -所有都是一个字符后跟 "at"
const regexWithWildcard = /.at/gi; //全部,忽略大小写
const testString = "cat BAT cupcake fAT mat dog";
const allMatchingWords = testString.match(regexWithWildcard); // ["cat", "BAT", "fAT", "mat"]

一个字符位置上可能出现字符集合的匹配

  • 使用字符类表达式,它可以定义一个字符集合匹配字符串中指定的字符位
  • 将字符集合放到 []
    // 匹配  "cat" "fat" 和 "mat" ,但是不匹配 "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) // 全匹配,返回原始串 "Emma19382"

匹配一个未知字符(排除已知字符)

  • 匹配不想要的字符集合,可以使用 否定表示符 表示排除的字符集合
  • 使用脱字符 ^ 表示排除字符集
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'];

匹配字符出现0次或多次

  • 使用星号 *
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"],其中 [a-z]* 匹配了 "atas"
testString.match(lazyRegex); // ["cat"],其中 [a-z]*? 仅匹配了 "a"

匹配字符串行首

  • 匹配计算从字符串行首开始,使用脱字符 ^,这种情况,脱字符 ^ 不在字符集表示符 [] 里,与排除字符集语法 [^abc] 区分。
const emmaAtFrontOfString = "Emma likes cats a lot.";
const emmaNotAtFrontOfString = "The cats Emma likes are fluffy.";
const startingStringRegex = /^Emma/; //匹配行首是 "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$/; //匹配以 "Emma" 结尾的字符串

startingStringRegex.test(emmaAtBackOfString); // true
startingStringRegex.test(emmaNotAtBackOfString); // false

匹配所有的字母和数字

  • 使用 \word 的简写 \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 改成大写 \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 = /\D/g;
sentenceWithWhitespace.match(nonWhiteSpaceRegex); // ["C", "a", "t"]

字符匹配次数指定

  • 可指定匹配字符的匹配次数范围,形式为 {下限, 上限}
const regularHi = "hi";
const mediocreHi = "hiii";
const superExcitedHey = "heeeeyyyyy!!!";
const excitedRegex = /hi{1,4}/; // i 紧接在 h 后出现1到4次都匹配

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

字符匹配次数仅下限指定

  • 只指定次数指定形式中的下限,如 {下限}
  • 这常被称为数量指示
const regularHi = "hi";
const mediocreHi = "hiii";
const superExcitedHey = "heeeeyyyyy!!!";
const excitedRegex = /hi{2,}/; // i 紧接在 h 后2次即匹配(可多不能少)

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

匹配准确的出现次数

  • 使用一个数的形式 {次数} 表示准确的出现次数
const regularHi = "hi";
const bestHi = "hii";
const mediocreHi = "hiii";
const excitedRegex = /hi{2}/; // 表示仅 i 在 h 后出现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
本文中的所有译文仅用于学习和交流目的,转载请务必注明文章译者、出处、和本文链接
我们的翻译工作遵照 CC 协议,如果我们的工作有侵犯到您的权益,请及时联系我们。

原文地址:https://dev.to/emmawedekind/regex-cheat-...

译文地址:https://learnku.com/f2e/t/38157

本文为协同翻译文章,如您发现瑕疵请点击「改进」按钮提交优化建议
讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!