gpt4 book ai didi

python - 在不知道变量名称的情况下返回正则表达式变量

转载 作者:行者123 更新时间:2023-12-01 04:48:46 25 4
gpt4 key购买 nike

我有这行代码:

hdfs_regex = re.compile(r'\s+(?P<unmatched>\d+)\s+\/\s+(?P<total>\d+)')

我运行一个文件并使用:

results = re.search(hdfs_regex, line)

查找 line 中的部分与我的正则表达式匹配。匹配后,有没有办法返回每个找到的匹配的正则表达式变量?

有没有找到返回的地方group不知道正则表达式变量名称?

伪代码可能看起来像这样

grouped_val = [i for i in results.grouped()]

哪里results.grouped()是一个可迭代对象,我可以使用它来检索找到的值,而无需知道变量名称

最佳答案

您可以使用groups()返回一个包含匹配模式的所有子组的元组:

>>> m = re.search(r"(\d+)\.?(\d+)?", "24.13244")
>>> m.groups()
('24', '13244')

groups([default]) Return a tuple containing all the subgroups of the match, from 1 up to however many groups are in the pattern. The default argument is used for groups that did not participate in the match; it defaults to None. (Incompatibility note: in the original Python 1.5 release, if the tuple was one element long, a string would be returned instead. In later versions (from 1.5.1 on), a singleton tuple is returned in such cases.)

关于python - 在不知道变量名称的情况下返回正则表达式变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28859282/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com