Python children's programming-09 regular

In addition to basic syntax and common operators, regular expressions also have some advanced features, such as greedy matching, non-greedy matching, pre-search, backreference, etc.

Greedy matching means that the regular expression will match as many characters as possible by default. For example, the regular expression "a.b " will match the longest string starting with "a" and ending with "b", even if the string contains multiple "b" characters. Non-greedy matching does the opposite, matching as few characters as possible. For example, the regular expression "a. ?b" will match the shortest string starting with "a" and ending with "b", even if the string contains multiple "b" characters.

Pre-search means that during the matching process, some restrictive conditions are first judged to reduce the number of backtracking and improve matching efficiency. For example, the regular expression "(?=pattern)" means to match the position before the pattern, but not including the pattern itself. Back reference means that during the matching process, "\n" (n is a number) can be used to refer to the previous grouping for subsequent matching. For example, the regular expression "(\w)\1" means match any repeated word characters.

In addition to these advanced features, regular expressions also have some commonly used metacharacters and escape characters, such as \d (matching digits), \s (matching whitespace characters), \w (matching word characters), \b (matching word boundaries ), \n (matches a newline), etc. These metacharacters and escape characters can help us match text more conveniently.

In conclusion, regular expressions are a very powerful tool that can be used to process all kinds of text data. When using regular expressions, you need to choose the appropriate matching mode and operator according to the actual situation, and you also need to pay attention to the performance and backtracking problems of regular expressions. If you want to learn more about regular expressions, you can refer to some excellent regular expression tutorials and examples, as well as the relevant chapters of the official Python documentation.
Ok, here are some examples of regular expressions combined with code:

  1. matches all numbers in a string
import re

text = "Today is 2023/6/20, and the time is 17:29:53"
pattern = r"\d+"
result = re.findall(pattern, text)
print(result)  # ['2023', '6', '20', '17', '29', '53']

In this example, we have used the regular expression "\d+" to match one or more digits. Use the re.findall function to return a list of all matching results.

  1. matches all words in a string
import re

text 

Guess you like

Origin blog.csdn.net/gaoxiangfei/article/details/131312000