6 – M5 SC 6 Metacharacters Part 1 V1

In the previous lessons, you learned how to use the backslash meta character to create special sequences. We will now look at the following metacharacters. The dot, the caret, and the dollar sign. Let’s start by looking at the dot. As we saw before, the dot matches any character except newline characters. Let’s see an example. Let’s use the dot as a regular expression to match all the characters in this multiline string. If we run this code, we can see that we match all the characters except newline characters. Now, let’s take a look at the caret. Here, we have a string that has the word “this” in two different places. The first instance of the word “this” occurs at the beginning of the string, while the second instance of the word “this” occurs towards the end of the string. If we use “this” as a regular expression, we will match both of these instances as we can see here. Now, let’s suppose we only wanted to match the word “this” that is at the beginning of the string. To do this, we can add the caret before the word “this” in a regular expression. The caret is used to much a sequence of characters only when they are located at the beginning of a string. So this regular expression will only match the word “this” if it’s located at the beginning of the string. If we run this code, we can see that we only get one match which corresponds to the “this” that is at the beginning of the sentence. Notice that it didn’t match the second instance of the word “this” because it wasn’t at the beginning of the string. Now, let’s take a look at the dollar sign. Here, we have a string with the word “watch” in two different places. The first instance of the word “watch” occurs towards the beginning of the string and the second instance of the word “watch” occurs at the end of the string. If we use “watch” as a regular expression, we will match both of these instances as we can see here. Now, let’s suppose we only wanted to match the word “watch” that appears at the end of our string. To do this, we can add the dollar sign after the word “watch” in our regular expression. The dollar sign is used to match a sequence of characters only when they are located at the end of a string. So this regular expression will only match the word “watch” if it is located at the end of a string. So if you run this code, we can see that we only get one match corresponding to the “watch” that is at the end of the string. Notice that it didn’t match the first instance of the word “watch” because it wasn’t at the end of the string.

%d 블로거가 이것을 좋아합니다: