python - Regular expression to extract software version from the given text?
问题描述
I am looking for a regular expression that can extract the software version from a string. Few samples look like
1) 'ABCD 2.3.4'
o/p: 2.3.4
2) 'ANDROID 4.4 KIT KAT SELFIX'
o/p: 4.4
3) '0.1.0-D-20170309.1502'
o/p: 0.1.0
4) 'CONTIXO-LA703-20180915-v1.0'
o/p: 1.0
My regex condition failing and unable to satisfy all these conditions. Here is my regex:
''.join(re.findall("[0-9.]", txt))
This can only satisfy the first two cases. How can I extract the software version from all the above cases?
Note: My old question was not specific and was closed without a solution. I deleted the question and added a new one. Hope this one meets the standard.
解决方案
In Python3: Use following, in case there are multiple matches present get the first one.
import re
re.findall('\d+(?:\.\d+)+', '3) \'0.1.0-D-20170309.1502\'')[0]
'0.1.0'
re.findall('\d+(?:\.\d+)+', '2) \'ANDROID 4.4 KIT KAT SELFIX\'')[0]
'4.4'
Explanation: Adding detailed explanation for above.
\d+ ##Looking for digits 1 or more occurrences here.
(?:\.\d+)+ ##Starting a non-capturing group which looks for a literal DOT followed by one or more
##digits occurrences AND one or more occurrences of this non-capturing group with `+` it will match.
As per The fourth bird's nice comment, you could try following too:
(?<![\d-])\d+(?:\.\d+)+
推荐阅读
- r - 无法加载包(例如:googlesheets)
- spring - NoSuchElement 执行 mvn 测试后不存在值
- javascript - 如何设置包含 D3 热图的 svg 元素的背景颜色?
- unit-testing - 跳过单元测试,但从 PyCharm 手动运行它
- gitlab - 添加用户应用程序的权限在哪里?
- automation - Ansible linefile 模块的属性行未在服务器上添加环境变量
- sql - SQL - 用 JSON 字符串中的回车和换行替换字符
- laravel - Laravel 5.6 设置迁移可为空的外国 id
- ios - iOS:CGRasterData 不包含在应用程序内存中,为什么?
- facebook-graph-api - 让 og:video 播放内联 whatsapp 和 facebook