如何在Python中匹配这种字符串使用re?

2024-10-01 00:21:52 发布

您现在位置:Python中文网/ 问答频道 /正文

我有几个类似的字符串:

unicode 0, <runtime error >,0
unicode 0, <TLOSS error>
unicode 0, <- Attempt to use MSIL code >
unicode 0, <ModuleNameA>

我正在尝试使用re来匹配“<;”“>;”中的所有字符串

我试过这个:

items = line.split()
pattern = r"<.+?>"
match = re.findall(pattern, items[2])

但似乎空间是无法处理的。。你知道吗

谁能帮我一下吗?你知道吗

谢谢你!你知道吗


Tags: to字符串ltreuseunicodecodeitems
2条回答

items[2]包含部分内容:

>>> items = line.split()
>>> items[2]
'<runtime'

只需将line传递给re.findall

>>> line = 'unicode 0, <runtime error >,0'
>>> re.findall(r'<.+?>', line)
['<runtime error >']

只是不要把它们分开,像这样用绳子

line = "unicode 0, <runtime error >,0"
import re
print(re.findall(r"<.+?>", line))
# ['<runtime error >']

如果你只想要里面的字符串,你可以这样做

print(re.search(r"<(.+?)>", line).group(1))
# runtime error 

相关问题 更多 >