代码之家  ›  专栏  ›  技术社区  ›  Forrest

使用lookahead regex拆分字符串

  •  0
  • Forrest  · 技术社区  · 7 年前

    我有这个字符串:

    {"TimePeriod": {"Start": "2017-03-01", "End": "2017-04-01"}, "Total": {"UnblendedCost": {"Amount": "2942.25119998", "Unit": "USD"}, "UsageQuantity": {"Amount": "20835", "Unit": "Hrs"}}, "Groups": [], "Estimated": false},
    {"TimePeriod": {"Start": "2017-04-01", "End": "2017-05-01"}, "Total": {"UnblendedCost": {"Amount": "2982.62609983", "Unit": "USD"}, "UsageQuantity": {"Amount": "21049", "Unit": "Hrs"}}, "Groups": [], "Estimated": false},
    {"TimePeriod": {"Start": "2017-05-01", "End": "2017-06-01"}, "Total": {"UnblendedCost": {"Amount": "1399.04829988", "Unit": "USD"}, "UsageQuantity": {"Amount": "23010", "Unit": "Hrs"}}, "Groups": [], "Estimated": false},
    {"TimePeriod": {"Start": "2017-06-01", "End": "2017-07-01"}, "Total": {"UnblendedCost": {"Amount": "962.47549987", "Unit": "USD"}, "UsageQuantity": {"Amount": "20049", "Unit": "Hrs"}}, "Groups": [], "Estimated": false}
    

    我正在使用一个正则表达式将上述字符串拆分为多个记录,例如:每条记录如下所示:

    {"TimePeriod": {"Start": "2017-06-01", "End": "2017-07-01"}, "Total": {"UnblendedCost": {"Amount": "962.47549987", "Unit": "USD"}, "UsageQuantity": {"Amount": "20049", "Unit": "Hrs"}}, "Groups": [], "Estimated": false}
    

    我目前的做法是

    (\{\"TimePeriod\":){1}.+(false\}){1}
    

    但这将匹配整个字符串,而不是匹配每个记录,我认为解决方案应该是使用regex中的lookahead来确保 时间段 在匹配的字符串中只出现一次,但我不知道如何执行。任何指点都将不胜感激。

    *每行之间没有换行符,我只是把它放在那里做演示

    2 回复  |  直到 7 年前
        1
  •  1
  •   Thm Lee    7 年前

    这似乎适合你的需要。我只是稍微把你的正则表达式改成 lazy 搜索模式 .+? 从…起 greed .+

    (\{\"TimePeriod\":){1}.+?(false\}){1}
    

    Demo

    如果再加上一些修改

    (\{\"TimePeriod\":).+?(false\})
    

    另一种使用前瞻的方法,

    (\{\"TimePeriod\":)(?:(?!false).)+(false\})
    
        2
  •  0
  •   Tim Biegeleisen    7 年前

    您可以在以下情况下进行拆分:

    ,(?=\{"TimePeriod":)
    

    Demo

    逻辑基本上是在一个逗号紧跟文本的位置拆分 {"TimePeriod": 。请注意,这意味着文本的开头不会有拆分,因为没有逗号。