我有这个字符串:
{"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}
但是这会匹配整个字符串而不是匹配每个记录,我认为解决方案应该是正则表达式中的前瞻,以确保 TimePeriod 在匹配的字符串中只出现一次,但我不知道我知道怎么做。任何指针都将受到赞赏。
*每一行之间没有换行符,我只是把它放在那里进行演示
答案 0 :(得分:1)
这似乎适合您的需要。我只是将你的正则表达式从lazy
.+?
greed
搜索模式.+
(\{\"TimePeriod\":){1}.+?(false\}){1}
如果添加了更多修改,那么它将是
(\{\"TimePeriod\":).+?(false\})
使用前瞻的另一种方法
(\{\"TimePeriod\":)(?:(?!false).)+(false\})
答案 1 :(得分:0)
您可以拆分以下内容:
,(?=\{"TimePeriod":)
逻辑基本上表示在文本{"TimePeriod":
后面紧跟着逗号的位置拆分。请注意,这意味着在文本的最开头没有拆分,因为没有逗号。