当子元素中有空格时,如何解析由空格分隔的字符串?

时间:2014-05-26 16:21:39

标签: java regex

输入字符串是这样的,每个元素由一个空格分隔:

"Fri, 23 May 2014 10:17:54 -0400 (EDT)" "This is a subject" ((NIL NIL \"10013001906\" \"domainname\"))

输出应该是String数组:

a[0] = "Fri, 23 May 2014 10:17:54 -0400 (EDT)",a[1] = "This is a subject",a[2] = ((NIL NIL \"10013001906\" \"domainname\"))

我有一个java版正则表达式工作,这里是示例代码:

private static void parseWholeEnvelope(){
String envelope = "\"Tue, 29 Sep 2009 12:00:00 +0100\" \"IMAPenvelope   test\""
     +" ((\"Test User1\" NIL \"testuser\" \"imaptest.net\"))"
     +" ((\"Test User2\" NIL \"testuser\" \"imaptest.net\"))"
     +" ((\"Test User3\" NIL \"testuser\" \"imaptest.net\"))"
     +" ((\"IMAP User\" NIL \"imap\" \"imaptest.net\")"
     +  " (\"Another User\" NIL \"a.n.other\" \"imaptest.net\"))"
     +" NIL NIL NIL"
     +" \"<4A671940.7030003@imaptest.net>\"";
String pattern4Envelope = "((\\((\\([^\\)]+\\)\\s*)+\\))|(\"[^\"]*\")|(NIL|\"[^\"]* \"))+?";
Pattern pattern = Pattern.compile(pattern4Envelope, Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(envelope);
while (matcher.find()) {
    System.out.println("Found the text \"" + matcher.group()
    + "\" starting at " + matcher.start()
    + " index and ending at index " + matcher.end());
}
}

1 个答案:

答案 0 :(得分:0)

可以用于此特定实例的Somethihg是:

Regex reg = new Regex("\" [\"(]");

或者您将用于您的语言的任何内容。这个查找引号后跟一个空格,然后是另一个引号或开放的括号。

你遇到的唯一问题是,它会将结束报价从第一个,第二个的开盘价和第三个的开盘价中拼接出来。不幸的是,由于我的知识有限,我不能为你做得更好。

收率:

string[0] = "Fri, 23 May 2014 10:17:54 -0400 (EDT)
string[1] = This is a subject
string[2] = (NIL NIL \"10013001906\" \"domainname\"))

转义序列和引号不用于简化输出。