gpt4 book ai didi

python - 在Python中制作正则表达式

转载 作者:太空宇宙 更新时间:2023-11-03 21:27:43 27 4
gpt4 key购买 nike

如何在 Python 中为此创建正则表达式?

[1,12:12] call basic_while1() Error Code: 1046. No database selected

我尝试了这个 '^\[(\d+),([0-9:]+)\]\s+(.+)$' 但我没有得到任何匹配项输入类型:使用该正则表达式['1','12:12', 'call basic_while1()' ,'错误代码: 1046.未选择数据库']。

and what is the regex if I want to get output like ['Error Code: 1046. No database selected']

如何为此创建正则表达式以便我可以获得匹配项?

最佳答案

在这里,我做出一个(有风险的)假设:您的文本中始终存在子字符串Error Code。所以我将你的正则表达式修改为 '^\[(\d+),([0-9:]+)\]\s+(.+)\s+(Error\sCode:.+)$'。在 shell 中运行:

>>> import re
>>> text = '[1,12:12] call basic_while1() Error Code: 1046. No database selected'
('1', '12:12', 'call basic_while1() Error Code: 1046. No database selected')
>>> re.match('^\[(\d+),([0-9:]+)\]\s+(.+)\s+(Error\sCode:.+)$', text)
<re.Match object; span=(0, 68), match='[1,12:12] call basic_while1() Error Code: 1046. N>
>>> _.groups()
('1', '12:12', 'call basic_while1()', 'Error Code: 1046. No database selected')

如果您想要一个列表,只需使用类型转换即可。

>>> list(_)
['1', '12:12', 'call basic_while1()', 'Error Code: 1046. No database selected']

旁注:上述命令中的 _ 是一个快捷方式,告诉 Python shell 重用之前的结果(在本例中为 re.Match对象,然后是 groups() 结果)。

总共:

matches = re.match('^\[(\d+),([0-9:]+)\]\s+(.+)\s+(Error\sCode:.+)$', text)
if matches is not None: # if there is no match, re.match returns None
print(list(matches.groups()))

and what is the regex if I want to get output like ['Error Code: 1046. No database selected']

您可以简单地使用 [-1] 索引列表的最后一个元素,然后用括号将其括起来以使其成为列表。

print([matches.groups()[-1]])  # output => ['Error Code: 1046. No database selected']

关于python - 在Python中制作正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53743938/

27 4 0
文章推荐: python - 使用 Python Docker API 从 tar 创建 docker
文章推荐: c# - 无法使用 Lambda 的扩展方法访问实例变量
文章推荐: html -
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com