Keep in mind that the compile() method is useful for defining and creating regular expressions object initially and then using that object we can look for occurrences of the same pattern inside various target strings without rewriting it which saves time and improves performance.Īnother benefit is readability. Now, the same reagex_pattern object can be used similarly for searching for three consecutive digits in other target strings as well.Ĭompiling regular expression objects is useful and efficient when the expression will be used several times in a single program. Next, we used the re.Pattern object inside a re.findall() method to obtain all the possible matches of any three consecutive digits inside the target string.The re.compile() method changed the string pattern into a re.Pattern object that we can work upon.# find all the matches in second string by reusing the same patternĪs you can see, we found four matches of “three consecutive” digits inside the first string. Str2 = "Kelly's luck numbers are 111 212 415" Regex_pattern = re.compile(string_pattern) # compile string pattern to re.Pattern object # pattern to find three consecutive digits In simple words, it means to match any three consecutive digits inside the target string such as 236 or 452, or 782.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |