另一个答案是,由于您似乎只专注于
String拆开(恕我直言,这不是一个好主意)。我们假设字符串是有效的ISO8601。您可以假设它 始终
是您引用的形式,还是仅适用于8601?如果是后者,则您必须像这些家伙那样应付一堆场景。
他们提出来验证8601替代方案的正则表达式是:
^([+-]?d{4}(?!d{2}b))((-?)((0[1-9]|1[0-2])(3([12]d|0[1-9]|3[01]))?|W([0-4]d|5[0-2]) (-?[1-7])?|(00[1-9]|0[1-9]d|[12]d{2}|3([0-5]d|6[1-6])))([Ts]((([01]d|2[0-3]) ((:?)[0-5]d)?|24:?00)([.,]d+(?!:))?)?(17[0-5]d([.,]d+)?)? ([zZ]|([+-])([01]d|2[0-3]):?([0-5]d)?)?)?)?$
弄清楚如何挑出正确的捕获组,这让我显得有些呆滞。不过,以下将适用于您的特定情况:
import java.util.regex.Matcher;import java.util.regex.Pattern;public class Regex8601{ static final Pattern r8601 = Pattern.compile("(\d{4})-(\d{2})-(\d{2})T((\d{2}):"+ "(\d{2}):(\d{2})\.(\d{3}))((\+|-)(\d{2}):(\d{2}))"); //2010-09-18T10:00:00.000+01:00 public static void main(String[] args) { String thisdate = "2010-09-18T10:00:00.000+01:00"; Matcher m = r8601.matcher(thisdate); if (m.lookingAt()) { System.out.println("Year: "+m.group(1)); System.out.println("Month: "+m.group(2)); System.out.println("Day: "+m.group(3)); System.out.println("Time: "+m.group(4)); System.out.println("Timezone: "+m.group(9)); } else { System.out.println("no match"); } }}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)