我正在努力寻找正确的正则表达式来解析包含键/值对的字符串。当字符串不被双引号引起来时,应在空格处进行分割。
示例字符串:
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,当不在正则表达式的单引号或双引号引起来时,使用空格分割字符串:
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"
part(在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"
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句