我正在编写一个从JSON收集数据的应用程序。我有一个字符串,叫做#34; opening_hours"从这个字符串我需要获得有关每周每一天的信息(我不知道如何解释......)
示例是:"Mon: 11:00 – 22:00 Tue: 11:00 – 22:00 Wed: 11:00 – 22:00 Thu: 11:00 – 5:00 Fri: 10:00 – 6:00 Sat: 11:00 – 6:00 Sun: 12:00 – 23:00"
从这个例子中我应该得到14个变量或一个数组,例如,它看起来像这样:
[0]=> 11:00
[1]=> 22:00
[2]=> 11:00
etc..
实现这一目标的最简单方法是什么?
提前致谢! 我很抱歉 - 我的英语不是很好。
答案 0 :(得分:1)
这是一个快速解决方案:
private static enum WeekDay {
Mon, Tue, Wed, Thu, Fri, Sat, Sun
}
private static class DaySchedule {
WeekDay weekDay;
LocalTime startTime;
LocalTime endTime;
public DaySchedule(WeekDay weekDay, LocalTime startTime, LocalTime endTime) {
this.weekDay = weekDay;
this.startTime = startTime;
this.endTime = endTime;
}
@Override
public String toString() {
return weekDay + " : " + startTime + " - " + endTime;
}
}
public static void main(final String[] args) {
final String in = "Mon: 11:00 – 22:00 Tue: 11:00 – 22:00 Wed: 11:00 – 22:00 " +
"Thu: 11:00 – 5:00 Fri: 10:00 – 6:00 Sat: 11:00 – 6:00 Sun: 12:00 – 23:00";
final Iterable<String> tokens = Splitter.on(" ").omitEmptyStrings().trimResults().split(in);
final Iterable<String> scheduleTokens = Iterables.filter(tokens, new Predicate<String>() {
@Override
public boolean apply(String input) {
return input.length() > 2;
}
});
final DateTimeFormatter localTimeFormatter = DateTimeFormat.forPattern("HH:mm");
final List<DaySchedule> schedule = Lists.newArrayList();
final Iterator<String> it = scheduleTokens.iterator();
while (it.hasNext()) {
final WeekDay day = WeekDay.valueOf(it.next().replaceAll(":", ""));
final LocalTime startTime = localTimeFormatter.parseLocalTime(it.next());
final LocalTime endTime = localTimeFormatter.parseLocalTime(it.next());
schedule.add(new DaySchedule(day, startTime, endTime));
}
System.out.println(schedule);
}
答案 1 :(得分:0)
使用包“java.util.regex”中的正则表达式。如果您100%确定String将始终使用相同的格式,那么它们是最佳解决方案。
这个答案不是正则表达式教程的最佳位置,所以在这里看一下Javadoc:
http://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html
关于正则表达式的和java教程:
http://docs.oracle.com/javase/tutorial/essential/regex/index.html
答案 2 :(得分:0)
您可以使用Pattern
en Matcher
String info = "Mon: 11:00 – 22:00 Tue: 11:00 – 22:00 Wed: 11:00 – 22:00 Thu: 11:00 – 5:00 Fri: 10:00 – 6:00 Sat: 11:00 – 6:00 Sun: 12:00 – 23:00";
Pattern p = Pattern.compile("(5:00|6:00|10:00|11:00|12:00|22:00|23:00)");
Matcher m = p.matcher(info);
List<String> theList = new ArrayList();
while(m.find()) {
theList.add(m.group());
}
theList.stream().forEach((item) -> {
System.out.print(item + ", ");
});
打印出来:
11:00, 22:00, 11:00, 22:00, 11:00, 22:00, 11:00, 5:00, 10:00, 6:00, 11:00, 6:00, 12:00, 23:00