DEV Community

Joe Lee
Joe Lee

Posted on

Intro to RegEx

Regular expressions, or RegEx, are versatile and powerful string patterns that are often used to match against strings for operations such as find, find and replace, and input validation. Another crucial aspect is that RegEx is widely supported by many languages.

However, it's infamous for its crazy syntax.

For example, this is the RegEx for a valid email address:

/^[a-zA-Z0-9.!#$%&’*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/
Enter fullscreen mode Exit fullscreen mode

Almost enough to make Siri wince ._.'

Good thing this is an intro!

RegEx uses '/' as delimiters, so /a/ would detect all of the 'a's in a string for you to then manipulate further. Note that it is case-sensitive.

If you wanted to look for multiple characters, then simply wrap them in brackets like so: /[abc]/

Or perhaps you want to look for a specific order of characters instead, then the RegEx would be like: /[h][i]/ for all instances of an 'h' followed by an 'i'.

To cast a wider net: /[abc][def]/ for any 'a', 'b', or 'c' that is then followed by any 'd', 'e', 'f'.

You can put in a range like so: /[a-c][1-3]/

For multiple consecutive characters try: /[abc]{2}/ which is the same as /[abc][abc]/

Which you can also put in a range: /[abc]{2-5}/ for [abc] 2-5 consecutive times, or simply {2,} for 2 or more occurrences.

There is a lot more you can do to build RegEx's as you can tell from the email example, but now what do we actually do with them?

Typically, they are paired with methods like .match, .replaceAll, and .search.

You can find more information here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions

Also, this site is a great interactive resource if you would like to dive right in: https://regexr.com/

Top comments (0)