在Python中使用正则表达式提取多个值

2024-09-25 06:23:04 发布

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

我想在python中使用正则表达式提取几个值

字符串是id : NAA1, priority : 4, location : WJQ, director : 13, text : HelloWorld

“NAA1,4,WJQ,13,HelloWorld”是我想要的价值。你知道吗

第一次,我试着这样做

import re
msg = "id : NAA1, priority : 4, location : WJQ, director : 13, text : HelloWorld"
_id = re.search('id : (.*?),', msg)

但我希望所有的值只使用一个重模式匹配。你知道吗


Tags: 字符串textimportreidsearchmsglocation
3条回答

用途:

import re
msg = "id : NAA1, priority : 4, location : WJQ, director : 13, text : HelloWorld"
print(re.findall(r' : ([^,]*)', msg))

输出:

['NAA1', '4', 'WJQ', '13', 'HelloWorld']
import re
STRING_ = "id : NAA1, priority : 4, location : WJQ, director : 13, text : HelloWorld"
re.findall(r':([\s\w\d]+)',STRING_)
>>>[' NAA1', ' 4', ' WJQ', ' 13', ' HelloWorld']

正则表达式在“:”之后查找每个字符串,直到找到一个空格。要使它对整个字符串起作用,应该在其末尾添加一个空格。你知道吗

import re
string = string + ' '
result = re.findall(': (.*?) ', string)
print(' '.join(result))

相关问题 更多 >