【问题标题】:Python split strings between " \" " into array of valuesPython将“\”之间的字符串拆分为值数组
【发布时间】: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。对其进行解码、循环,然后将正则表达式应用于您的问题。

标签: python json regex


【解决方案1】:

为什么不试试这些re.findall("thing[^\[]*\([^\]]*\]", message_string)

【讨论】:

  • 再次,很想尝试一下,但thing 在真正的字符串中不是一个常用词。我提供了一个错误的样本。
【解决方案2】:

re.findall 很好地完成了工作。

import re

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]\"."}'
result = re.findall('thing[0-9] \([a-z]*\/[a-z]*\) \[Phase [0-9]\]',message_string)  
print(result)

输出:

[
    "thing2 (ug/g) [Phase 1]", 
    "thing3 (pass/fail) [Phase 1]", 
    "thing4 (pass/fail) [Phase 1]", 
    "thing5 (pass/fail) [Phase 1]"
]

【讨论】:

  • 它不会返回 OP 想要的所有值。
  • 对于示例中没有更清楚的说明,我深表歉意。 thing1, thing2, thingN 实际上是不同的词。
猜你喜欢
  • 1970-01-01
  • 2020-07-21
  • 1970-01-01
  • 2016-04-01
  • 2017-11-07
  • 2012-02-22
相关资源
最近更新 更多