2011-03-02 19 views
0

我有這個字符串解析字符串爲標記立足崗位

「名稱,展會開始於14/08/09,您的機票是在14/08/09預訂」

在此字符串我想要獲得值StartDate,預訂日期和姓名作爲個人令牌。這應該適用於所有字符串在相同的格式

我如何解析它們在java中?

+2

XML在哪裏適合? – 2011-03-02 19:48:14

+0

'StartDate'和'bookedDate'是那些字符串值還是它們應該是日曆對象? – Woot4Moo 2011-03-02 19:51:01

回答

1

我希望人們會非常迫切地想要推薦的正則表達式,但我不認爲他們始終提供最佳的解決方案。他們可能很難閱讀,而且更難調試。所以作爲替代方案,我建議String.split():

String line = "Name, Show starts on 14/08/09, your ticket is booked on 14/08/09"; 
    String[] parts = line.split("[ ,]"); // ie split on comma or space 

    String name = parts[0]; 
    String showDate = parts[5]; 
    String bookDate = parts[12]; 

    System.out.println(name + ":" + showDate + ":" + bookDate); 
+0

我正在推薦StringTokenizer,但是它的JavaDoc實際上建議在新代碼中使用String.split :) – 2011-03-02 20:23:50

+0

這種方法存在一個缺陷:如果名稱包含空格,則索引將不同,例如「John Doe,....」 - > showDate = parts [6]。 如果只有名稱可以更改,您應該先做按「,」拆分,然後再根據需要拆分個別令牌。 – Thomas 2011-03-03 07:05:58

2

因此,如果格式相同,您可以使用正則表達式並將值收集到組中。

事情是這樣的:

String input = "Name, Show starts on 14/08/09, your ticket is booked on 14/08/09"; 
String regex = "([a-zA-Z \t]*),.*(\\d\\d/\\d\\d/\\d\\d),.*(\\d\\d/\\d\\d/\\d\\d)"; 
Pattern pattern = Pattern.compile(regex); 
Matcher matcher = pattern.matcher(input); 
if(matcher.matches() && matcher.groupCount() == 4) //group 0 is always the entire expression 
{ 
    String name = matcher.group(1); 
    String startDate = matcher.group(2); 
    String bookedDate = matcher.group(3); 
} 
+0

我在String正則表達式序列中出錯 - 無效的轉義序列(有效的轉義序列是\ b \ t \ n \ f \ r \「\'\\) – 2011-03-02 20:05:39

+0

使用\\ d而不是\ d應該有幫助 – Boris 2011-03-02 20:07:57

+0

是的,我測試過這個表達式在一個現場評估者中忘了逃避Java字符串中的\字符:) 感謝您的編輯 – Thomas 2011-03-02 20:17:51

0

這個怎麼樣?

String s = "Name, Show starts on 14/08/09, your ticket is booked on 14/08/09"; 

String wordsPattern = "[\\w\\s]+"; 
String datePattern = "\\d{1,2}\\/\\d{1,2}\\/\\d{1,2}"; 
Pattern p = Pattern.compile(String.format("(%s),%s(%s),%s(%s)", wordsPattern, wordsPattern, datePattern, wordsPattern, datePattern)); 

SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yy"); 
Matcher m = p.matcher(s); 
m.find(); 

String name = m.group(1); 
Date startDate = sdf.parse(m.group(2)); 
Date bookedDate = sdf.parse(m.group(3)); 

System.out.println("name: " + name); 
System.out.println("startDate: " + startDate); 
System.out.println("bookedDate: " + bookedDate); 

結果: -

name: Name 
startDate: Wed Apr 08 00:00:00 CDT 2009 
bookedDate: Wed Apr 08 00:00:00 CDT 2009