我有这个字符串
“姓名,节目于2009年8月14日开始,您的机票将于2009年8月14日预订”
在这个字符串中,我希望获得值StartDate,scheduledDate和nameofthePerson作为单独的标记。这应该适用于所有相同格式的字符串
我如何在java中解析它们?
答案 0 :(得分: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);
}
答案 1 :(得分: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);
答案 2 :(得分: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