In the previous lesson, we looked at terms used in regular expressions. In this video, we’ll see 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.
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.
Don't worry about flags for now. We’ll learn more about that in the next video.
Like I said, languages also have other ways to create regular expressions.
you use 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.
new RegExp(pattern, flags)
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.
A Simple regular expression
Like I said in the intro video, we will be testing the regular expressions that we create in this course on this website…
Here, we can specify the language…
Here, we can enter a string and pattern, as see the matches in the string. We already have the forward slash at the beginning and at the end on this website, so we don’t need to write that again.
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/:
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/
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.
Now these are just simple examples of regular expressions. /name/, /code/--easyyyy!
In the next video, we'll learn about flags, and then we'll learn about more advanced ways of creating regular expressions.