DEV Community

Cover image for Practical Applications for Regex
Katherine Peterson
Katherine Peterson

Posted on • Updated on • Originally published at

Practical Applications for Regex

Regular expressions can be hard to understand and difficult to learn. However, they are extremely powerful and have many use cases in the real world. In this post, I will explore some practical applications of regex.

Form Field Validation

One of the most common use cases for regex is validating form fields such as emails, usernames, credit card numbers, phone numbers, dates, password strength, etc.

The following example is a regex that validates the format of an email.

const emailValidatorRegex = /^[^@\s]+@[^@\s]+\.[^@\s\.]{2,}$/

function isValid(email) {
    if emailValidatorRegex.test(email) {
        return true
    } else {
        return false

isValid('') // true 
isValid('dummyemail@gmail') // false

Enter fullscreen mode Exit fullscreen mode

Find and Replace

Regex can be used to write complex find and replace functions. You can even use regex to find and replace inside editors like VSCode.

The following example takes all normal javascript function declarations and replaces them with arrow functions.

const normalFunction = `
function add(x, y) {
    return x + y

const arrowFunction = normalFunction.replace(/function\s*(\w+)\s*\(([^\)]+)\)/g, "const $1 = ($2) =>")

const add (x, y) => {
    return x + y
Enter fullscreen mode Exit fullscreen mode

Here is how you could use this to find and replace in VSCode.

Using Regex for find and replace in VSCode

HTML Parsing

Another use case for regex is for parsing things like HTML. Maybe you want to extract image sources from some HTML or extract all the URLs from a Google search result.

Let's say you have some HTML, and you want to extract everything that is inside of an <li> and put it into an array. Here's how we could do this.

const markup = `

    <h1>Shopping List</h1>


      <li>Ice Cream</li>
      <li>Hot Pockets</li>


const listParser = /(?<=<li>)(\w|\s)+(?=<\/li>)/gm

const shoppingList = markup.match(listParser)

// [ 'Celery', 'Apples', 'Ice Cream', 'Hot Pockets' ]

Enter fullscreen mode Exit fullscreen mode


There is so much you can do with regular expressions. However, they are definitely not the solution to everything. Despite their power and flexibility, they are not the most readable for other developers.

Maybe don't reach for it for something like trimming whitespace from a string. There are string methods or basic functions for this. But for complex search, find and replace, validation, and parsing, regular expressions are a great solution. Plus, they are fun to write!

Want to learn regex?

Check out my interactive course:

Follow me on Twitter for updates:

Top comments (0)