re模块是Python中用来处理正则表达式的工具包,re.search.span是其下的一个函数,可以用来查找字符串中匹配正则表达式的子串的位置。
使用方法
函数原型:re.search(pattern, string, flags=0)
该函数会在目标字符串string中搜索与正则表达式pattern 匹配的子串,返回一个MatchObject 对象。如果没有找到匹配的子串,返回None。
具体使用方法:
-
导入 re 模块
-
使用 search 函数实例化一个匹配对象,并传入两个必须参数,即希望匹配的字符串和正则表达式:
import re
text = 'This is a string with some numbers 12345 and a symbol $'
match = re.search(r'\d+', text)
- 如果得到了匹配对象,即不为 None,则可以使用 match.span() 方法来获得匹配对象的位置,函数返回匹配对象的起始位置和结束位置:
span() 函数返回 tuple 类型,其中第一个元素为起始位置,第二个元素为结束位置。 例如:
if match:
print('Match found from {} to {}'.format(match.span()[0], match.span()[1]-1))
实例1
text = 'I am 18 years old and she is 20 years old.'
match = re.search(r'\d+', text)
if match:
print('Match found from {} to {}'.format(match.span()[0], match.span()[1]-1))
输出:
Match found from 7 to 8
实例2
text = 'The price of the product is 123.45 yuan.'
match = re.search(r'\d+\.\d+', text)
if match:
print('Match found from {} to {}'.format(match.span()[0], match.span()[1]-1))
输出:
Match found from 23 to 27
在这两个例子中,我们使用了一个正则表达式来匹配两个不同类型的数字,使用 re.search 函数查找匹配对象,并使用 span 函数返回了其位置。