DEV Community

loading...

Javascript Regex Part 2 Character Classes

scdan0624 profile image SCDan0624 ・1 min read

Intro

In my part one of my previous post I displayed how to find literal pattern matches. If you need to search for a literal pattern with some flexibility you can use regex character classes.

Character Classes

Character classes allow you to define a set of characters you wish to match by using square brackets:

let myPet = "cat"
let notMyPet = "cut"
let myRegex = /c[au]t/

myPet.match(myRegex) // Returns ["cat"]
notMyPet.match(myRegex) // Returns ["cut"]
Enter fullscreen mode Exit fullscreen mode

Match a Range

If you need to match a large set of letters you can also define a range using a hyphen:

let myPet = "cat"
let notMyPet = "bat"
let forMyFloor = "mat"
let myRegex = /[b-m]at/

myPet.match(myRegex) // Returns ["cat"]
notMyPet.match(myRegex) // Returns ["bat"]
forMyFloor.match(myRegex) // Returns ["mat"]
Enter fullscreen mode Exit fullscreen mode

You can also a hyphen to match any number in a string:

let myName = "Dan061983"
let myRegex = /[a-z0-9]/ig // Will match all letters and numbers in myName
myName.match(myRegex)
Enter fullscreen mode Exit fullscreen mode

Discussion (0)

pic
Editor guide