Convert, or unformat, a string to variables (like format(), but in reverse) in Python

前端 未结 7 2370
[愿得一人]
[愿得一人] 2020-12-15 03:44

I have strings of the form Version 1.4.0\\n and Version 1.15.6\\n, and I\'d like a simple way of extracting the three numbers from them. I know I

7条回答
  •  生来不讨喜
    2020-12-15 03:55

    Actually the Python regular expression library already provides the general functionality you are asking for. You just have to change the syntax of the pattern slightly

    >>> import re
    >>> from operator import itemgetter
    >>> mystr='Version 1.15.6\n'
    >>> m = re.match('Version (?P<_0>.+)\.(?P<_1>.+)\.(?P<_2>.+)', mystr)
    >>> map(itemgetter(1), sorted(m.groupdict().items()))
    ['1', '15', '6']
    

    As you can see, you have to change the (un)format strings from {0} to (?P<_0>.+). You could even require a decimal with (?P<_0>\d+). In addition, you have to escape some of the characters to prevent them from beeing interpreted as regex special characters. But this in turm can be automated again e.g. with

    >>> re.sub(r'\\{(\d+)\\}', r'(?P<_\1>.+)', re.escape('Version {0}.{1}.{2}'))
    'Version\\ (?P<_0>.+)\\.(?P<_1>.+)\\.(?P<_2>.+)'
    

提交回复
热议问题