简体   繁体   English

如何从字符串中使用定界符提取数字?

[英]How to extract numbers with delimiter from a string?

I am trying to extract the numbers with delimiters from a filename (for version check purpose). 我试图从文件名中提取带有定界符的数字(用于版本检查)。 I have the filename as filename= bacserv.v1.2.6 and not with quotes ('') . 我的文件名是filename= bacserv.v1.2.6not with quotes ('') I am using RegEx as below but RegEx takes the input as 'bacserv.v1.2.6' with quotes. 我正在按以下方式使用RegEx,但是RegEx将输入作为带有引号的'bacserv.v1.2.6' My expected output is 1.2.6 or "1.2.6" . 我的预期输出是1.2.6"1.2.6" Can anyone help? 有人可以帮忙吗?

import re
matches = re.findall('\d+', 'bacserv.v1.2.6')
print(matches)

Output: 输出:

['1', '2', '6']

use re.search with slightly different pattern: 使用re.search的模式略有不同:

import re
match = re.search('\d+.\d+.\d+', 'bacserv.v1.2.6')
if match:
   version = match.group()

您可以将正则表达式结果更进一步,然后应用'.'.join(matches)

How about the following? 接下来呢? Assuming the version number always follows ".v" in the filename: 假定版本号在文件名中始终跟随“ .v”:

import re
m = re.search('(\.v)([\d\.]+)', 'bacserv.v1.2.6')
print(m.group(2))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM