3 – M5 SC 3 Finding Metacharacters V1

Now, let’s try to use a regular expression to find this period at the end of our sentence. So, let’s use a period as a regular expression and let’s run this code just as we did before. We can see that something has gone wrong. The finditer method has matched every single character in our sample text including uppercase and lowercase letters, word space and the period at the end of our sentence. The reason it did that is because in regular expressions, the period is a special character known as a metacharacter. Metacharacters are used to give special instructions, and cannot be searched for directly. Here’s a complete list of the Metacharacters used in regular expressions, and we will learn how to use them in later lessons. If we want to search for this metacharacters in strings, we need to escape them first. Just like with Python string literals, we can use the backslash to escape all the metacharacters. So, now let’s try to find the period of the end of our sentence again, but this time we will use a backslash in our regular expression to remove the period special meaning. If we run this code, we will see that now the finditer method, only gets one match which corresponds to the period at the end of the sentence as we wanted.

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