python之正则表达式re入门系列

python re模块实际使用总结

# match: 从开头开始匹配,返回匹配的第一个结果
# eg:

def match(pattern, string, flags=0):
    """Try to apply the pattern at the start of the string, returning
    a Match object, or None if no match was found."""
    return _compile(pattern, flags).match(string)

match函数接收三个参数,分别是正则匹配模式(正则表达式), 要匹配的字符串, flags默认为0,没需求的话可以忽略
match函数会返回一个match对象(匹配成功), 或者None(正则表达式没有匹配字符串中的内容)
查看match函数返回的具体结果需要调用.group()方法

# 提取版本
string = '2.0.5-SNAPSHOP'

result = re.match('[0-9.]+', string)
result = re.match('[d.]+', string)
result = re.match('d.d.d', string)
print(result.group())

# search: 浏览全部字符在其中匹配符合规则的字符,返回匹配成功的第一个,或者None
# eg

def search(pattern, string, flags=0):
    """Scan through string looking for a match to the pattern, returning
    a Match object, or None if no match was found."""
    return _compile(pattern, flags).search(string)

# 获取版本信息
string = '>=1.1.4 <=2.2.3'

ret = re.search('[d.]+', string).group()
ret1 = re.search('<=[d.]+', string).group().replace('<=', '')
print(ret, ret1)

search 函数的参数和match相同, replace方法替换字符串,接收两个参数(old_str, new_str),老的替换成新的

原文地址:https://www.cnblogs.com/chaizhenhua/p/13636487.html