1.re.search(): search returns the object of the search result (after finding the first successfully matched result in order, it will not search further, and None will be returned if no result is found). You can use group() Or use the groups() method to get the successfully matched string.
①group() returns the entire string that matches successfully by default (ignoring the parentheses in pattern). You can also specify the string in the parentheses that matches successfully to return (counting from 1);
②groups() returns the content in the parentheses of the successfully matched pattern in the form of a tuple. If there are no parentheses in the pattern, it returns an empty tuple corresponding to the successfully matched string.
1 >>> string = 'python' 2 >>> import re 3 >>> result = re.search(r'(yt)h(o)', string) 4 >>> result 5 <_sre.SRE_Match object at 0x000000000293DE88> 6 >>> result.group() 7 'ytho' 8 >>> result.group(0) # 参数0无效 9 'ytho'10 >>> result.group(1) # 从1开始计数11 'yt'12 >>> result.group(2)13 'o'14 >>> result.groups()15 ('yt', 'o')16 >>> result.groups(0) # 传入参数无效17 ('yt', 'o')18 >>> result.groups(1)19 ('yt', 'o')20 >>>
2. re.finditer(): Returns an iterator of all search results (if there is no matching string, an empty iterator is returned), each iteration object You can also use group() and groups() to obtain the results of successful matches.
1 >>> string = 'one11python, two22, three33python ' 2 >>> result = re.finditer(r'(\d+)(python)', string) 3 >>> for p in result: 4 print(p.group()) 5 6 7 11python 8 33python 9 >>> for p in result:10 print(p.group(2))11 12 13 python14 python15 >>> for p in result:16 print(p.groups()) # 若是pattern中没有括号,则返回的是每个迭代器对应的空元组。17 18 19 ('11', 'python')20 ('33', 'python')
3. re.findall(): Returns all found strings in the form of a list (if no matching string is found, an empty list is returned) .
1 >>> string = 'one11python, two22, three33python '2 >>> result = re.findall(r'\d+python', string)3 >>> result4 ['11python', '33python']5 >>> result = re.findall(r'(\d+)(python)', string)6 >>> result7 [('11', 'python'), ('33', 'python')]
The above is the detailed content of Python re operation example tutorial. For more information, please follow other related articles on the PHP Chinese website!