In this article, we will introduce in detail the advanced knowledge about regular expressions, and I will write down some problems that may arise in python programming. Examples of regular expressions.
The first advanced knowledge point:
##Split string
Using regular expressions to split strings is more flexible than using fixed characters. Please see the normal splitting code:>>> 'a b c'.split(' ') ['a', 'b', '', '', 'c']
>>> re.split(r'\s+', 'a b c') ['a', 'b', 'c']
>>> re.split(r'[\s\,]+', 'a,b, c d') ['a', 'b', 'c', 'd']
>>> re.split(r'[\s\,\;]+', 'a,b;; c d') ['a', 'b', 'c', 'd']
Grouping
In addition to simply determining whether to match, regular expressions also have the powerful function of extracting substrings. What is represented by () is the group to be extracted. For example:^(\d{3})-(\d{3,8})$ defines two groups respectively, which can be extracted directly from the matching string Area code and local number:
>>> m = re.match(r'^(\d{3})-(\d{3,8})$', '010-12345') >>> m <_sre.SRE_Match object; span=(0, 9), match='010-12345' >>>> m.group(0) '010-12345' >>> m.group(1) '010' >>> m.group(2) '12345'
>>> t = '19:05:30' >>> m = re.match(r'^(0[0-9]|1[0-9]|2[0-3]|[0-9])\:(0[0-9]|1[0-9] |2[0-9]|3[0-9]|4[0-9]|5[0-9]|[0-9])\:(0[0-9]|1[0-9]|2[0-9]|3[0-9]|4[0-9]|5[0-9]|[0-9])$', t) >>> m.groups() ('19', '05', '30')
'^(0[1-9]|1[0-2]|[0-9])-(0[1-9]|1[0-9]|2[0-9]|3[0-1]|[0-9])$'
'2-30', '4-31' Such illegal dates cannot be identified using regular expressions, or it is very difficult to write them out. In this case, a program is required to cooperate with the identification.
The above is all the content of this article. This article mainly introduces the knowledge related to regular expressionsin python. I hope you can use the information to understand the above. content. I hope what I have described in this article will be helpful to you and make it easier for you to learn python.
For more related knowledge, please visit thePython tutorial column on the php Chinese website.
The above is the detailed content of Detailed explanation of regular expressions in python (example analysis). For more information, please follow other related articles on the PHP Chinese website!