Python 我想从字符串中提取/分析值

Python 我想从字符串中提取/分析值,python,python-2.7,Python,Python 2.7,我想从以下字符串中提取结束值: string1 = 'http://localhost/dir/file.js?ver=3.5.4' string2 = 'OneWord 2.5.4' 请注意,我要提取的这些(版本)数字值并非每次都相同 extracted1 = '3.5.4' extracted2 = '2.5.4' 用法: import re semver = r'\d+\.\d+\.\d+' def get_semver(string): return re.search(

我想从以下字符串中提取结束值:

string1 = 'http://localhost/dir/file.js?ver=3.5.4'
string2 = 'OneWord 2.5.4'
请注意,我要提取的这些(版本)数字值并非每次都相同

extracted1 = '3.5.4'
extracted2 = '2.5.4'
用法:

import re

semver = r'\d+\.\d+\.\d+'

def get_semver(string):
    return re.search(semver, string).group(0)


如果只想在字符串末尾匹配它们,请在正则表达式中添加一个
$

如果字符串保持不变,则表示URL,无论vesion编号是否不同,都可以使用以下代码。 实际上,你需要更清楚地知道你想要什么:

>>> get_semver(string1)
'3.5.4'
>>> get_semver(string2)
'2.5.4'

是否可以添加
$
以确保它只在末尾匹配?
string1 = 'http://localhost/dir/file.js?ver=3.5.4'
string2 = 'OneWord 2.5.4'
extracted1 = string1.split("=")[1]
extracted2= string2.split(" ")[1]