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