Python获取字符串中两个指定子串中间的数据

88 阅读1分钟

使用re模块中的findall函数,其中【.*?】也可以为【.+?】。

res = re.findall(r'前面的子串(.*?)后面的子串',输入的字符串)[0]


例1:搜索以【https://】开头,以【/html/】结尾的中间的内容

import re

str = "https://www.bt-tt.com/html/4/29110.html"
result = re.findall(r'https://(.*?)/html/',str)[0]  
print(result)   # 打印结果为:www.bt-tt.com

例2:搜索以【A】开头,以【B】结尾的中间的内容

import re

str = "AwdnmdB"
result = re.findall(r'A(.*?)B',str)[0]
print(result)  # 打印结果为:wdnmd