DEV Community

SCDan0624
SCDan0624

Posted on

1

Javascript Regex Part 2 Character Classes

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

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

Top comments (0)

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay