Regular Expressions 101: The Basics

Regular Expressions (regex) - the ultimate tool for text manipulation. But don't worry, we won't make you write a novel about it.

What is a Regular Expression?

A regex is a way to describe a pattern in text. Think of it like a super-powered version of a "Find and Replace" in your favorite text editor, but with more power and less patience.

Imagine you have a string of text and you want to find all occurrences of a certain pattern. A regex can do that for you, but with a twist: it can do it with style.

Let's look at an example:

.*(\d{4})

What this says is "find me any character (.) that is followed by exactly 4 digits (\d{4})". Sounds simple enough, right?

Now, if we want to find all occurrences of this pattern in the string "1234 is the best day ever!"

Here's what it looks like:

1234  is the best day ever!

Types of Regex

There are many types of regex, but don't worry, we'll cover the basics first. For now, let's focus on the three main types:

Literal Characters

Literal characters match exactly what's written. Simple enough, right?

Let's look at an example:

hello

This will match the string "hello" exactly, no more no less.

Metacharacters

Metacharacters match anything except what's written. Think of it as the opposite of Literal Characters.

Let's look at an example:

.* (any character except .)

This will match any string that contains any character except the dot (.) character.

Groups

Groups are used to group characters together. It's like putting parentheses around something.

Let's look at an example:

(\w+)

This will match any word (group of characters) that is 1 or more characters long.

That's it for today's lesson. You now know the basics of regex. Keep in mind, this is just the beginning. There's more to learn, but don't worry, it's worth it.

For more advanced lessons, check out our regex-201 page.