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

标签 python regex

如何在 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/

相关文章:

ruby - 如何在 Ruby 的子字符串中拆分 CamelCase 字符串?

python - 尝试将 SQL 查询转换为 SQLAlchemy 查询

regex - 当某个字符出现在另一个特定字符之后时不匹配的正则表达式?

python - Django MTM 字段 : limit_choices_to = other_ForeignKeyField_on_same_model?

python - 如何使用 python 正则表达式将路由 key 与 RabbitMQ 主题交换的绑定(bind)模式相匹配?

android - Gradle脚本XML转换

python - 尝试使用 RegEx 理解更简单的方法

java - 多项式表达式的正则表达式

python - 使用序列化程序从 URL 保存图像

python - Keras:处理线程和大型数据集