gpt4 book ai didi

java - 使用键/值对中的空格不被引号括起来的正则表达式拆分字符串

转载 作者:行者123 更新时间:2023-11-29 08:57:12 25 4
gpt4 key购买 nike

我正在努力寻找正确的正则表达式来解析包含键/值对的字符串。当字符串没有被双引号括起来时,应该用空格分隔。

示例字符串:

2013-10-26    15:16:38:011+0200 name="twitter-message" from_user="MyUser" in_reply_to="null" start_time="Sat Oct 26 15:16:21 CEST 2013" event_id="394090123278974976" text="Some text" retweet_count="1393"

期望的输出应该是

2013-10-26
15:16:38:011+0200
name="twitter-message"
from_user="MyUser"
in_reply_to="null"
start_time="Sat Oct 26 15:16:21 CEST 2013"
event_id="394090123278974976"
text="Some text"
retweet_count="1393"

我找到这个答案让我接近期望的结果 Regex for splitting a string using space when not surrounded by single or double quotes使用正则表达式:

Matcher m = Pattern.compile("[^\\s\"']+|\"[^\"]*\"|'[^']*'").matcher(str);
while (m.find())
list.add(m.group());

这给出了一个列表:

2013-10-26
15:16:38:011+0200
name=
"twitter-message"
from_user=
"MyUser"
in_reply_to=
"null"
start_time=
"Sat Oct 26 15:16:21 CEST 2013"
event_id=
"394090123278974976"
text=
"Some text"
retweet_count=
"1393"

它在 = 符号上拆分,因此在获得所需输出方面仍然缺少一些东西。

最佳答案

试试这个

[^\\s=]+(=\"[^\"]+\")?
  • [^\\s=]+ 会找到所有不是空格或 = 的东西,所以对于 start_time="Sat Oct 26 15:16:21 CEST 2013" 它将匹配 start_time 部分。
  • (=\"[^\"]+\")? 是可选的,它将匹配 ="zzz" 部分(其中 z 不能是 ")

例子

Matcher m = Pattern.compile("[^\\s=]+(=\"[^\"]+\")?").matcher(str);
while (m.find())
System.out.println(m.group());

输出:

2013-10-26
15:16:38:011+0200
name="twitter-message"
from_user="MyUser"
in_reply_to="null"
start_time="Sat Oct 26 15:16:21 CEST 2013"
event_id="394090123278974976"
text="Some text"
retweet_count="1393"

关于java - 使用键/值对中的空格不被引号括起来的正则表达式拆分字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19616323/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com