🏡 Home

Regular Expressions Note 2: match a group of characters, character negation, and at least one occurance

Part of my post series on learning regular expressions:

Matching a group of character

We can match a group of character by using the angle brackets []

const stringToMatch =
  "The big bug is in the bog not in the big. Please, I beg you not to bug the bug"
const bgRegex = /b[iua]g/g
const results = stringToMatch.match(bgRegex)

// results will be ["big", "bug", "big", "bug", "bug"]. `bog` and `beg` will be ignored

Matching a range of alphabets

We can add range to the group of character in the angle brackets []

const stringToMatch =
  "They ban the bin word. Others, circumvent this by changing the letter i with number 1 to become b1n"
const bnRegex = /b[a-z]n/gi
const results = stringToMatch.match(bnRegex)

// results will be ["ban", "bin"]

Matching a range of alphabets and numbers

The range in the previous group of character example did not match the numerics so the b1n was not matched. We can add numerics by addding the range in the angle brackets [] aside from the alphabets.

const stringToMatch =
  "They ban the bin word. Others, circumvent this by changing the letter i with number 1 to become b1n"
const bnRegex = /b[a-z0-9]n/gi
const results = stringToMatch.match(bnRegex)

// results will be ["ban", "bin", "b1n"]

Negating a character

We can add a character negation in the angle bracket using caret ^ (this is the alternate character on key 6 in the number rows if you are struggling searching it like me 😂)

const stringToMatch = "the bug is riding a bus on a bun"
const buRegex = /bu[^n]/gi
const results = stringToMatch.match(buRegex)

// results will be ["bug", "bus"]

Matching characters that occur at least once

Repeating characters on can be matched using the plus + sign in regex

const stringToMatch = "The bug is passing a gate"
const sRegex = /s+/g
const results = stringToMatch.match(sRegex)

// results will be ["s", "ss"]