Here is the video version for this topic. You can read the written version which comes after the video section.

In the previous lesson, we looked at terms used in regular expressions. In this video, we'll learn how to create a regular expression.

Different programming languages may have different syntax for constructing Regular expressions.

One common syntax that these programming languages have is the literal notation.

And then they can have other ways. For example in JavaScript, you can also use the RegExp constructor.

The syntax for the literal notation is: you have a forward slash, then you have your pattern, and end with the second forward slash. After the second forward slash, you can pass your flags. Flags are optional. You only use them when you need them.

/pattern/flags

Don't worry about flags for now. We'll learn more about that in the next lesson.

Like I said, languages also have other ways to create regular expressions.

Like I mentioned for JavaScript, you can use the RegExp constructor is:

new RegExp(pattern, flags)

By using the new keyword, and then the RegExp constructor, this means you are instantiating a RegExp object. The constructor accepts two arguments: the first one is the pattern, which can be a string, or a literal regex, and the second one is a string containing the flags. The flags are also optional, so you can pass only the first argument if you don't need them.

But we're not going to focus on JavaScript in this course.

In the coming videos, we'll learn about the various patterns we can create and flags we can use. But for this video, let’s look at a simple regular expression.

Let's say we have a simple string like "my name is Dillion". And we want to write a pattern that matches "name" in this string. Our regex pattern will be simply be /name/:

Regex/name/
Input
Match

As you can see, this pattern matches the "name" part in our full string. We can call this part a substring.

Let's look at another example. Say a string like "my channel is deeecode, and I make videos on code". And our pattern is simply: /code/

Regex/code/
Input
Match

As you can see, this pattern matches only one "code" substring, which is the one in "deeecode". But the second "code" is not matched. By default, a regex pattern only matches the first occurrence that fits the pattern. If we want to change the default behaviour of regex patterns, this is where we introduce flags.

Remember I said flags change the default behaviours of Regex.


In the next lesson, we'll learn about flags, and then we'll learn about more advanced ways of creating regular expressions.