JS common regular expression memo

Keywords: Front-end Asterisk

Matching regularization

Use the. test() method

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

Match multiple patterns

Use operation symbols|

const regex = /yes|no|maybe/;    

ignore case

Use the i flag to ignore case

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

Extract the first match of a variable

Use the. match() method

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

Extract all matches in the array

Use the "g" sign

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

Match any character

Use wildcards. As placeholders for any character

//To match "cat", "bat", "fat", "mat" const regexwithwildcard = /. At / GI; const teststring = "cat bat cupmake fat mat dog"; const allmatchingwords = teststring. Match (regexwithwildcard); / ["cat", "bat", "fat", "mat"] match a single character with multiple possibilities
  • Using the character class, you can use it to define a set of characters to match

  • Put them in square brackets []

//Match "cat" "fat" and "mat" but not "bat" const regexwithcharclass = / [CFM] at / g; const teststring = "cat fast bat mat"; const allmatchingwords = teststring.match (regexwithcharclass); / ["cat", "fat", "mat"]    

Match letters in alphabet

Use range in character set [a-z]

const regexWidthCharRange = /[a-e]at/;
const regexWithCharRange = /[a-e]at/;const catString = "cat";const batString = "bat";const fatString = "fat";
regexWithCharRange.test(catString); // trueregexWithCharRange.test(batString); // trueregexWithCharRange.test(fatString); // false

Match specific numbers and letters

You can also use hyphens to match numbers

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

Match a single unknown character

To match a set of characters you don't want, use the negative character set ^

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

Match one or more characters in a line

Use + sign

const oneOrMoreAsRegex = /a+/gi;const oneOrMoreSsRegex = /s+/gi;const cityInFlorida = "Tallahassee";
cityInFlorida.match(oneOrMoreAsRegex); // ['a', 'a', 'a'];cityInFlorida.match(oneOrMoreSsRegex); // ['ss'];   

Match zero or more consecutive characters

Use asterisk *

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

Inertia matching

  • The smallest part of a string that matches a given requirement

  • By default, regular expressions are greedy (matching the longest part of a string that meets a given requirement)

  • Use? Prevent greedy mode (lazy matching)

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

Match start string pattern

To test character matching at the beginning of a string, use the caret ^, but to enlarge the beginning, do not place it in the character set

const emmaAtFrontOfString = "Emma likes cats a lot.";const emmaNotAtFrontOfString = "The cats Emma likes are fluffy.";const startingStringRegex = /^Emma/;
startingStringRegex.test(emmaAtFrontOfString); // truestartingStringRegex.test(emmaNotAtFrontOfString); // false     

Match end string pattern

Use $to determine if a string ends with a specified character

const emmaAtBackOfString = "The cats do not like Emma";const emmaNotAtBackOfString = "Emma loves the cats";const startingStringRegex = /Emma$/;
startingStringRegex.test(emmaAtBackOfString); // truestartingStringRegex.test(emmaNotAtBackOfString); // false    

Match all letters and numbers

Use \ word shorthand

const longHand = /[A-Za-z0-9_]+/;const shortHand = /\w+/;const numbers = "42";const myFavoriteColor = "magenta";
longHand.test(numbers); // trueshortHand.test(numbers); // truelongHand.test(myFavoriteColor); // trueshortHand.test(myFavoriteColor); // true

Except for letters and numbers, everything else must match

Use \ w to indicate the antonym of \ w

const noAlphaNumericCharRegex = /\W/gi;const weirdCharacters = "!_$!!";const alphaNumericCharacters = "ab283AD";
noAlphaNumericCharRegex.test(weirdCharacters); // truenoAlphaNumericCharRegex.test(alphaNumericCharacters); // false

Match all numbers

You can use character set [0-9], or shorthand \ d

const digitsRegex = /\d/g;const stringWithDigits = "My cat eats $20.00 worth of food a week.";
stringWithDigits.match(digitsRegex); // ["2", "0", "0", "0"]

Match all non numeric

Use \ D for antonym of \ D

const nonDigitsRegex = /\D/g;const stringWithLetters = "101 degrees";
stringWithLetters.match(nonDigitsRegex); // [" ", "d", "e", "g", "r", "e", "e", "s"]

Matching spaces

Use \ s to match spaces and carriage returns

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

Match non spaces

Use \ s for antonym of \ s

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

Number of characters matched

You can use {lower bound, upper bound} to specify a specific number of characters in a line

const regularHi = "hi";const mediocreHi = "hiii";const superExcitedHey = "heeeeyyyyy!!!";const excitedRegex = /hi{1,4}/;
excitedRegex.test(regularHi); // trueexcitedRegex.test(mediocreHi); // trueexcitedRegex.test(superExcitedHey); //false

Matches the minimum number of characters

Use {lower bound,} to define the minimum number of character requirements. The following example indicates that the letter i must appear at least twice

const regularHi = "hi";const mediocreHi = "hiii";const superExcitedHey = "heeeeyyyyy!!!";const excitedRegex = /hi{2,}/;
excitedRegex.test(regularHi); // falseexcitedRegex.test(mediocreHi); // trueexcitedRegex.test(superExcitedHey); //false

Match exact number of characters

Use {requiredCount} to specify the exact number of character requirements

const regularHi = "hi";const bestHi = "hii";const mediocreHi = "hiii";const excitedRegex = /hi{2}/;
excitedRegex.test(regularHi); // falseexcitedRegex.test(bestHi); // trueexcitedRegex.test(mediocreHi); //false    

Match 0 or 1 times

Use? To match characters 0 or 1 times

const britishSpelling = "colour";const americanSpelling = "Color";const languageRegex = /colou?r/i;
languageRegex.test(britishSpelling); // truelanguageRegex.test(americanSpelling); // true

Posted by stone.cold.steve.austin on Mon, 23 Mar 2020 07:50:38 -0700