10+ Regex Examples for Developers

10+ Regex Examples for Developers

Having taken on some Algorithm problems that were easier to solve with Regex and some string manipulation methods in JS, I decided to dive further...

Regular expressions are patterns used to match character combinations in strings. Regex might differ in implementation across languages but the basics as we explore here are mostly the same. In JavaScript, regular expressions are also objects, in fact, everything is an object in JS, but that's not the topic for today.

These patterns are used with the exec() and test() methods of RegExp, and with the match(), matchAll(), replace(), replaceAll(), search(), and split() methods of String (MDN). Also regex matches return an array of the matched items or null

With Regex and the aforementioned object method combinations, you can achieve some very complex string manipulations. From solving basic algorithm problems like replacing whitespace in a string to implementing email validation.

Most of the below content are my attempt to try summarise this freecodecamp tutorial Regex - FreeCodeCamp by Beau Carnes as I went through the course myself.

A quick overview

Common regex methods used in this article are: test() and match(). test() returns true or false depending on whether or not the regex has a match in the string. match() returns the matched portion of the string.

Example 1: Match a simple string.

let sentence = "The dog chased the cat.";
let regex = /the/
let result = regex.test(sentence); 
// returns true

Given a string as in the variable let sentence, the regex /the/ attempts to match a string in the sentence variable with the same characters, with the .test method, true is returned to result variable.

Example 2: Match a literal string with different possibilities

let petString = "James has  a pet cat.";
let petRegex = /dog|cat|bird|fish/;
// returns "cat"

The pipe character (|) in regex means OR, this means we are trying to find either dog or cat or bird or fish from the string "petString". Using the ".test" method will return true if ANY of the string values is a match and false otherwise. The '.match' method will return any of the values that qualify.

Example 3: Using the 'i' flag to ignore case

let myString = "freeCodeCamp";
let fccRegex = /freecodecamp/i;
// returns "freecodecamp"

This example is quite similar to the previous one but note the "i" after the regex forward-slash /freecodecamp/i, That's a flag and we are going to use two common flags in this dive, the "i" flag for ignoring case and the g flag for global searching (meaning the regex should be tested against every string char and every instance returned, you will understand it more with the examples that follow).

Example 4: Find more than the first match with the 'g' flag

let testStr = "Repeat, Repeat, Repeat"
let ourRegex = /Repeat/g; 
// returns "Repeat, Repeat, Repeat" with the g flag
// returns "Repeat" without the g flag.

Without the "g" flag, the returned value will be the first matched value; using the g flag, means that every found instance should be returned. Both the g and i flags can be used for a combined effect.

Example 5: Match any char in the string ('the wildcard')

let humStr = "I'll hum a song";
let hugStr = "Bear hug";
let huRegex = /hu./;
let unRegex = /.un/;
// Returns ["hum"]
// Returns ["hug"]

Using the period "." in regex means that you are trying to match any character, in this case, huRegex will match any characters "hu" and any other character that follows, whereas unRegex will match any characters "un" and any other non-specific character before. Therefore the match for both patterns will be "hum" and "hug" respectively.

Example 6: Match single character with multiple possibilities

let bgRegex = /b[aiu]g/g; //* this will match bug, big and bug
let quoteSample = "Beware of big bugs in bags; I have experience";
// returns "big", "bug", "bag"

The "[]" in a regex can be understood as a shorthand form of the "|" operator. Therefore instead of writing /big|bug|bag/, you get to write /b[iau]g/, a shorthand.

Example 7: Match letters of the alphabet

let quoteSample = "The quick brown fox jumped over the lazy dog";
let alphabetRegex = /[a-z]/ig;
// returns all the letters of the alphabet, without the "g" flag it would only return the very first letter, "T".

The above regex matches all the English alphabets because [a-z] is a definition of a range of letters to be matched, in this case, all of them, if you should modify the regex to /[a-g]/ig, only the English letters a to g will be returned.

Example 8: Match a combination of letters and numbers.

let quoteSample = "The quick brown fox jumped over the lazy dog 12 11 0 1 2 3 4 5 6 7 8 9 10 11";
let alphabetRegex = /[0-9A-Z]/ig; 
// returns all the characters in the string

This regex means "match all numbers 0 to 9, also match all letters A-Z", therefore returning all the characters in the string.

Example 9: Match single characters not specified.

let quoteSample = "3 blind mice."
let myRegex = /[^0-9aeiou]/ig // ^ means negate the matches, return others instead.
// returns [' ', 'b', 'l','n', 'd', ' ','m', 'c', '.']

The "^" character in this regex negates the specified conditions after it, meaning: don't match these, return the opposite.

Example 10: Match characters that appear more than once

let quoteSample = "3 blind mices in Misssissippi."
let myRegex = /s+/ig 
// returns [ 's', 'sss', 'ss' ]

The '+' char in this regex means, find every instance of the preceding character, return in its repeated pattern, you can remove the '+' to see the effect.

Example 11: Match characters that appear 0 or more times

let soccerWord = "Gooooooal."
let gPhrase = "gut feeling";
let oPhrase = "over the moon"
let sRegex = /go*/ig; 
// returns ['Goooooo']
// [ 'g', 'g' ] and null

The '*' character in a regex matches the preceding character if it appears more than once or zero times, therefore in the first example, since 'G' is a match and there are more than one instances of 'o', ['Goooooo'] is returned. Since there is no instance of 'o' in the 'gPhrase' string, only the 'g' is returned. Null is returned from 'oPhrase' as there is no match for the regex.

Example 12: Find characters with lazy/greedy matching

let string = "titanic";
let regex = /t[a-z]*?i/; 
let regex2 = /t[a-z]*i/; 
// returns 'ti' with the '?' which means lazy matching and
// 'titani' without, which is greedy matching

To search the entire string for possible matches for the regex, greedy matching is used, to return a shallow match, lazy matching is used, lazily match a regex by adding the '?' as demonstrated in the code.

Another example:

let text = "<h1>Winter is coming</h1>"
let myRegex = /<.*?>/
// returns <h1> , would match the entire string without '?'

Example 13: Match beginning string patterns

let rickyAndCal = "Cal and Ricky both like racing."
let calRegex = /^Cal/;
// returns TRUE when the .test method is used to test the string, meaning the string does indeed begin with 'Cal'

'^' means the beginning of the string, in this regex we are checking that the beginning of rickyAndCal contains the characters 'Cal'.

Example 14: Match ending string patterns

let caboose = "The last car on a train is the caboose"
let lastRegex = /caboose$/;
// returns true when used with the .test() method

The '$' character in a regex is the opposite of the '^', '$' means the end of the string, whilst '^' means the start of the string.

Example 15: Match all letters and numbers

let quoteSample = "The five boxing wizards jump quickly"
let alphabetRegexV2 = /\w/g; 
// \w is a shorthand character class that will match [a-z][0-9] and _

The regex above returns all the alphanumeric characters of the string including underscore, as it matches a-z, 0-9 and _

Example 16: Match no letters or numbers or _

let quoteSample = "The five boxing wizards jump quickly"
let alphabetRegexV2 = /\W/g; 
// \W is a shorthand character class that will NOT match [a-z][0-9] or _

The REGEX in example 16 is the exact opposite of example 15.

Example 17: Match all numbers

let numString = "Your sandwich will be $5.00";
let numRegex = /\d/g; 
// returns all numbers, in this case [5, 0, 0]

The above regex will return all the numbers in the test string as shown and all non-number characters when the uppercase /\W /is used.

Example 18: Match whitespace

let sample = "Whitespace is important in separating words.";
let countWhiteSpace = /\s/g; 
// returns all the whitespace in the text

Lowercase 's' matches whitespace, Using uppercase S returns non-whitespace chars instead.

Example 19: Specify Upper and Lower number of matches

let ohStr = "Ohhh no";
let ohRgex = /Oh{3,} no/;
// returns 'Ohhh no'

{3, upperboundValue} means match 3 or specified number of 'h', an upper bound and a lower bound of 'h' characters. Therefore the regex will match either 3 'h's or below, if an upper bound value is added the regex will match the number of characters between 3 and the upper, this regex will return true for .test and Ohhh no for .match, you can test the regex to further understand this.

Example 20: Specify the exact number of matches

let timStr = "Hazzzzah"
let timRegex = /Haz{4}/;
// returns  'Hazzzz'

Match like the previous example but without the comma, this regex specifies that a string 'Haz' with specifically 4 z characters be matched, therefore the resulting Hazzzz being returned.

Example 21: Check for All or None

let favWord = "favorite"
let favRegex = /favou?rite/;
// returns "favourite" but will also return "favorite" if favWord is modified in that manner.

The '?' character in this regex checks if the preceding character, 'u' in this case is either present or not, therefore, this regex will match both 'favorite' and 'favourite'.

Example 22: Positive and Negative Lookahead

let quit = "qu";
let noquit = 'qt';
let quRegex = /q(?=u)/; // + lookahead
let qRegex = /q(?!u)/; // - lookahead
// quRegex returns 'u' (positive)
// qRegex returns

Positive lookahead means: match the characters but only return the characters that precede the lookup definition, In quRegex, 'q' precedes the 'u', therefore the 'q' or any string of characters that matched will be returned but not the 'u'. Negative lookahead is the exact reverse of a positive lookup, whereas positive returns the characters before the definition, negative returns the characters after the lookup definition.

Example 23: Reuse patterns using capture groups

let repeatStr = "regex regex";
let repeatRegex = /(\w+)\s\1/; // reads as any number of characters capture group, whitespace, repeat capture group.
repeatStr.match(repeatRegex)
// Returns "regex regex"

Capturing groups are a way to treat multiple characters as a single unit. They are created by placing the characters to be grouped inside a set of parentheses. For example, the regular expression (dog) creates a single group containing the letters "d" "o" and "g". The above regex will match and return 'regex regex' because the capture group (\w+) is treated as a unit and matched. If it's still confusing feel free to jump into regexr.com to test it out.

Quick Test

1. Find one or more of a character:

let crowd = 'P1P2P3P4P5P6CCCP7P8P9';
// From what you have learnt so far, try to write a regex to find one or more 'C's in the string

2. Validating a username:

let username = "JackOfAllTrades"; Write a regex to .test() the following conditions on the given username.

  1. If there are numbers, they must be at the end.
  2. Letters can be lowercase and uppercase.
  3. At least two characters long. Two-letter names can't have numbers.

You can use this great Regex tool to generate your regexes: REGEXR

I shall return with more interesting writeups as I write and read more code, learn and level up. Thank you for reading.

Further Reading

Visit MDN's docs for further information on Regex and advanced usage.