JS Common Regular Expression Memo

Keywords: Javascript Asterisk React Java

Summary: Play with regular expressions.

Fundebug Copyright shall be owned by the original author when authorized to reproduce.

Below the parts of a regular expression or "regex" used to match strings is my memo for creating regular expressions.

Matching Regular

Using the.test() method

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

Match multiple patterns

Use Operational Symbols|

const regex = /yes|no|maybe/;    

ignore case

Use the i flag to indicate ignoring 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

Using the.match() method

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

Extract all matches from an array

Use g flag

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

Match any character

Use wildcards. Placeholders for any character

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

Matching a single character with multiple possibilities

  • With a 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 fat bat mat";
const allMatchingWords = testString.match(regexWithCharClass); // ["cat", "fat", "mat"]    

Match letters in the alphabet

Use ranges within the 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); // true
regexWithCharRange.test(batString); // true
regexWithCharRange.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 to have, use the negative character set ^

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

Match characters that appear once or more in a line

Use + Flag

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

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

Match characters that appear zero or more times in a row

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

Inert 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 patterns (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); // true
startingStringRegex.test(emmaNotAtFrontOfString); // false    

BUGs that may exist after code deployment are not known in real time. In order to solve these BUGs afterwards, a lot of time has been spent debugging the log. By the way, a useful BUG monitoring tool is recommended. Fundebug.

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); // true
startingStringRegex.test(emmaNotAtBackOfString); // false    

Match all letters and numbers

Short form using \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

Match everything except letters and numbers

Use \W to denote the antisense of \w

const noAlphaNumericCharRegex = /\W/gi;
const weirdCharacters = "!_$!!";
const alphaNumericCharacters = "ab283AD";

noAlphaNumericCharRegex.test(weirdCharacters); // true
noAlphaNumericCharRegex.test(alphaNumericCharacters); // false

Match all numbers

You can use the character set [0-9], or the abbreviation\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-numbers

Use \D for the antisense of \d

const nonDigitsRegex = /\D/g;
const stringWithLetters = "101 degrees";

stringWithLetters.match(nonDigitsRegex); // [" ", "d", "e", "g", "r", "e", "e", "s"]

Match Spaces

Use\s to match spaces and carriage returns

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

Match non-whitespace

Use \S to denote the antisense of \s

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

Number of characters matched

You can specify a specific number of characters in a line using {Lower Bound, Upper Bound}

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

Number of characters matching the lowest number

Using the {lower bound,} to define a minimum number of character requirements, the following example shows 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); // false
excitedRegex.test(mediocreHi); // true
excitedRegex.test(superExcitedHey); //false

Match exact number of characters

Use {requiredCount} to specify the exact number of characters required

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  

Match 0 or 1 times

Use? Match characters 0 or 1 time

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

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

About Fundebug

Fundebug Focus on JavaScript, WeChat applets, WeChat games, Alipay applets, React Native, Node.js, and real-time BUG monitoring for Java online applications.Since the official launch of November 11, 2016, Fundebug has handled a cumulative billion + error events. Payment customers include Google, 360, Jinshan Software, People's Network and many other brand enterprises.Welcome Free Trial!

Posted by bigfunkychief on Sat, 04 May 2019 21:40:39 -0700