【发布时间】:2021-03-06 13:52:29
【问题描述】:
在这里有点挣扎,可能需要一些专业知识。
示例字符串:
(单字符串但多行代码在这里被围起来,所以它不会跑出屏幕)
message_string = '{"Message": "Lab Test Type \"thing1 [Phase 1]\"requires the following additional Lab Test Types to be recordedwhen Passing: \"thing2 (ug/g) [Phase 1]\", \"thing3 (pass/fail[Phase 1]\", \"thing4 (pass/fail) [Phase 1]\", \"thing5(pass/fail) [Phase 1]\"."}'
所需状态:
[
"thing2 (ug/g) [Phase 1]",
"thing3 (pass/fail) [Phase 1]",
"thing4 (pass/fail) [Phase 1]",
"thing5 (pass/fail) [Phase 1]"
]
正则表达式尝试:
import re
split_message = re.split('\\\"([^\\\"]*)\\\",', message_string)
结果:
[
'{"Message": "Lab Test Type \"thing1 [Phase 1]\" requires the following additional Lab Test Types to be recorded when Passing: ',
'thing2 (ug/g) [Phase 1]',
' ',
'thing3 (pass/fail) [Phase 1]',
' ',
"thing4 (pass/fail) [Phase 1]",
' ',
"thing5 (pass/fail) [Phase 1]"."}'
]
问题:
- 如何剥离最初的
{"Message...元素?所有的空格 (' ') 和最后的."},这样剩下的只是一个带有things的数组?
编辑 1:
- 我应该在示例中更清楚。
thing1, thing2, thingN可以是任何字符串;实际上,它们是不同的词。 - @anubhava 的解决方案让我最接近。
- 我不清楚为什么我需要用
r''' ... '''包围message_string。必须重新搜索,因为在使用 Python 之前我没有遇到过这种语法。 - 我可能需要负前瞻才能从结果中消除
thing1。
【问题讨论】:
-
不要使用
split。使用re.findall(r'\\"(.*?)\\"', string) -
该示例字符串是 JSON。对其进行解码、循环,然后将正则表达式应用于您的问题。