我有一些行代表文本文件中的一些数据。它们都是以下格式:
s = 'TheBears SUCCESS Number of wins : 14'
它们都以名称开头,然后是空格和文本“SUCCESS Number of wins :”,最后是获胜次数 n1。有多个字符串,每个字符串具有不同的名称和值。我正在尝试编写一个程序来解析这些字符串中的任何一个并返回数据集的名称和字符串末尾的数值。我正在尝试使用正则表达式来执行此操作,并且我想出了以下内容:
import re
def winnumbers(s):
pattern = re.compile(r"""(?P<name>.*?) #starting name
\s*SUCCESS #whitespace and success
\s*Number\s*of\s*wins #whitespace and strings
\s*\:\s*(?P<n1>.*?)""",re.VERBOSE)
match = pattern.match(s)
name = match.group("name")
n1 = match.group("n1")
return (name, n1)
至此,我的程序可以返回名字,但是麻烦就来了。他们都有文本“SUCCESS Number of wins :”所以我的想法是找到一种方法来匹配这个文本。但我意识到我现在匹配精确子串的方法不正确。有什么方法可以匹配整个子字符串作为模式的一部分吗?我最近读了很多关于正则表达式的书,但还没有找到这样的东西。我对编程还是很陌生,感谢您的帮助。
最终,我将使用 float() 将 n1 作为一个数字返回,但我将其遗漏了,因为它现在不能正确地首先找到数字,只会返回一个错误。
最佳答案
试试这个:
((\S+)\s+SUCCESS Number of wins : (\d+))
结果如下:
>>> regex = re.compile("((\S+)\s+SUCCESS Number of wins : (\d+))")
>>> r = regex.search(string)
>>> r
<_sre.SRE_Match object at 0xc827cf478a56b350>
>>> regex.match(string)
<_sre.SRE_Match object at 0xc827cf478a56b228>
# List the groups found
>>> r.groups()
(u'TheBears SUCCESS Number of wins : 14', u'TheBears', u'14')
# List the named dictionary objects found
>>> r.groupdict()
{}
# Run findall
>>> regex.findall(string)
[(u'TheBears SUCCESS Number of wins : 14', u'TheBears', u'14')]
# So you can do this for the name and number:
>>> fullstring, name, number = r.groups()
如果您不需要完整的字符串,只需删除圆括号即可。
关于Python Regex 匹配字符串作为模式并返回数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6377707/