我有這個字符串解析字符串爲標記立足崗位
「名稱,展會開始於14/08/09,您的機票是在14/08/09預訂」
在此字符串我想要獲得值StartDate,預訂日期和姓名作爲個人令牌。這應該適用於所有字符串在相同的格式
我如何解析它們在java中?
我有這個字符串解析字符串爲標記立足崗位
「名稱,展會開始於14/08/09,您的機票是在14/08/09預訂」
在此字符串我想要獲得值StartDate,預訂日期和姓名作爲個人令牌。這應該適用於所有字符串在相同的格式
我如何解析它們在java中?
我希望人們會非常迫切地想要推薦的正則表達式,但我不認爲他們始終提供最佳的解決方案。他們可能很難閱讀,而且更難調試。所以作爲替代方案,我建議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);
我正在推薦StringTokenizer,但是它的JavaDoc實際上建議在新代碼中使用String.split :) – 2011-03-02 20:23:50
這種方法存在一個缺陷:如果名稱包含空格,則索引將不同,例如「John Doe,....」 - > showDate = parts [6]。 如果只有名稱可以更改,您應該先做按「,」拆分,然後再根據需要拆分個別令牌。 – Thomas 2011-03-03 07:05:58
因此,如果格式相同,您可以使用正則表達式並將值收集到組中。
事情是這樣的:
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);
}
這個怎麼樣?
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
XML在哪裏適合? – 2011-03-02 19:48:14
'StartDate'和'bookedDate'是那些字符串值還是它們應該是日曆對象? – Woot4Moo 2011-03-02 19:51:01