avatarMatt Croak Code

Summary

This article provides guidance on matching multiple conditions in regular expressions (regex), demonstrating how to combine patterns efficiently and use special characters.

Abstract

The article delves into the use of regex for pattern matching, specifically focusing on combining multiple conditions into a single regex statement. It begins by illustrating how to match uppercase and lowercase letters, then progresses to matching whole words like "love." The author explains the use of character classes and the importance of escaping special characters, such as parentheses, when they are part of the search pattern. The post also covers the logical OR operator, represented by the pipe |, to find instances of either one pattern or another. The article concludes with practical examples, including finding emoticons in a string, and emphasizes the need to escape special regex characters to ensure accurate matching.

Opinions

  • The author emphasizes the efficiency and cleanliness of combining multiple regex conditions into one statement.
  • They suggest that using a single regex statement with multiple conditions is preferable to multiple separate statements.
  • The author provides a real-world application of regex by showing how to match specific words and emoticons in text.
  • The article encourages readers to explore further regex resources and invites them to share their own methods for using multiple conditions in regex.
  • The author promotes their Medium Partner Program account and newsletter subscription, indicating a desire to grow their audience and share more content on regex and related topics.

How To Match Multiple Conditions in Regex

Combine Regex to Have Clean, Efficient Pattern Matching

Photo by Nubelson Fernandes on Unsplash

In a previous post, I wrote about how to make YouTube links show up as thumbnails in your Medium post. In order to do it, you need to make use of some regular expressions to match and replace certain patterns in the provided URLs.

In the post, I included a bonus section where one might encounter two different conditions that need to be accounted for. You could do two separate statements to address both cases. Or, you can do it the clean, efficient way by incorporating multiple conditions into one regex statement.

In this post, I’ll dive a little more in depth on how to do this! Below, is a simple regex that can be used in conjunction with match so that you can find whatever parts of a string meet your regex condition.

const line = 'My name is Matthew Croak. I love the NY Mets.';
const regex = /[A-Z]/g;
const found = line.match(regex);

console.log(found)

> (7) ['M', 'M', 'C', 'I', 'N', 'Y', 'M']

The above code is trying to find all characters in the string that are uppercase letters. Now, what if we wanted to match all uppercase and lowercase letters? Let’s update our regex to be const regex = /[A-Za-z]/g;.

Our result should look like the below.

['M', 'y', 'n', 'a', 'm', 'e', 'i', 's', 'M', 'a', 't', 't', 'h', 'e', 'w', 'C', 'r', 'o', 'a', 'k', 'I', 'l', 'o', 'v', 'e', 't', 'h', 'e', 'N', 'Y', 'M', 'e', 't', 's']

This is great! What if we wanted to match a whole word? Let’s say, love? We can do it like this!

const line = 'My name is Matthew Croak. I love the NY Mets.';
const regex = /love/g;
const found = line.match(regex);

console.log(found)

> ['love']

Seems easy enough right? If we kept love in the brackets, like /[love]/g, we’d end up with the below value.

> (9) ['e', 'e', 'o', 'l', 'o', 'v', 'e', 'e', 'e']

This is because the brackets are used as a “character class”. That means “any character from a,b or c”. A character class may use ranges, e.g. [a-d] = [abcd]). You can see the original Stack Overflow explanation here.

Multiple Conditions

Back to the original purpose of the post: How To Use Multiple Conditions in Regex?

Let’s say we wanted to find the words love and Mets. We can write the below regex making use of a pipe ( | ).

const line = 'My name is Matthew Croak. I love the NY Mets.';
const regex = /love|Mets/g;
const found = line.match(regex);

console.log(found)

> ['love', 'Mets']

The pipe indicates a logical OR expression. It can be used when you want to find instances of either one pattern OR another. If we used, say, a space in between love and Mets, or if we used nothing between them at all, we’d get nothing back from our regex.

This is because the match pattern is now either loveMets or love Mets — neither of which appear in the string. We need the pipe in order to execute the OR logic.

Get all of my latest content by creating a Medium Partner Program account and subscribing to my emails. :)

This OR operator can be used with many different conditions, not just two! Check it out. Let’s look for Matthew, love, and Mets.

const line = 'My name is Matthew Croak. I love the NY Mets.';
const regex = /love|Mets|Matthew/g;
const found = line.match(regex);

console.log(found)

> ['Matthew', 'love', 'Mets']

Notice how the order in which I include the match patterns don’t matter? It’ll still find the matches and log them in the order in which they appear in the string.

Let’s try something a bit more complex.

Multiple Conditions (with Special Characters)

Check out this line.

const line = "My name is Matthew Croak :). I <3 the NY Mets (not so much the yankees but they're OK.)";

Let’s say we want to find all emoticons. Try the below in your console.

const line = "My name is Matthew Croak :). I <3 the NY Mets (not so much the yankees but they're OK).";
const regex = /<3|:)/g;
const found = line.match(regex);

console.log(found)

What happened? When you logged it? Did it look like this…

Uncaught SyntaxError: Invalid regular expression: /<3|:)/: Unmatched ‘)’

Why did this happen? Well, it’s because ) is a special character in regex! It’s used for grouping. In order to find it in our string, we’ll have to escape it with a backslash.

See below.

const regex = /<3|:\)/g;

Our updated code should give us the below response.

> (2) [':)', '<3']

There you have it! How to combine multiple regex expressions into one by using the logical OR operator. You also learned how to escape special or reserved characters so you can find them in a string!

For more regex related resources, checkout my collated regex list!

Do you have another way to use multiple conditions in regex? Let me know in the comments!

Upgrade your free Medium membership and receive unlimited, ad-free, stories from thousands of writers on a wide variety of publications. This is an affiliate link and a portion of your membership helps me be rewarded for the content I create.

You can also subscribe via email and get notified whenever I post something new!

References

JavaScript
Regex
Regular Expressions
Programming
Software Development
Recommended from ReadMedium