有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java正则表达式来检测此模式

我有以下格式,我想用正则表达式检查它:

2016-05-24T22:00:00

如果我想用简单的java操作来实现它,那将非常简单。但我认为在regx中执行更有效。有人能帮我怎么用regx吗?(我对regex完全陌生)


共 (5) 个答案

  1. # 1 楼答案

    由于您不熟悉正则表达式,让我们看看您需要匹配什么:

    • 日期(明确采用YYYY-MM-dd格式)
    • 时间(以T开头,格式为hh:mm:ss

    因此,您实际上只需要匹配一些特定字符(-T:),而其他所有字符都只是一个数字\d。因此,匹配符合此模式的任何数字的非常基本的示例可能如下所示:

    \d{4}\-\d{2}\-\d{2}T\d{2}:\d{2}:\d{2}
    

    这是在做什么

    \d{4}       # Matches four consecutive digits (year)
    \-          # Matches an explicit dash (separating years and months)
    \d{2}       # Matches two consecutive digits (months)
    \-          # Matches another dash (months and days)
    \d{2}       # Matches two more digits (days)
    T           # Matches a T (indicating the start of your time)
    \d{2}       # Matches two digits (hours)
    :           # Matches a colon (between hours and minutes)
    \d{2}       # Matches two more digits (minutes)
    :           # Matches another colon (minutes and seconds)
    \d{2}       # Finally, matches two digits for seconds
    

    这显然是一个非常基本的方法,正如Thomas' response所看到的,它肯定可以缩短。我只是想帮助您了解如何构造表达式来解决这个问题

  2. # 2 楼答案

    我将使用SimpleDateFormat。它有你需要的一切,比如检查小时数是否符合数字范围。您可以跳过这些检查,否则这对正则表达式来说是一项可怕的任务

  3. # 3 楼答案

    此正则表达式执行以下工作:

    \d{4}(?:-\d{2}){2}T\d{2}(?::\d{2}){2}
    

    demo。说明:

    \d{4} match a digit [0-9]
    
        Quantifier: {4} Exactly 4 times
    
    (?:-\d{2}){2} Non-capturing group
    
        Quantifier: {2} Exactly 2 times
        - matches the character - literally
        \d{2} match a digit [0-9]
            Quantifier: {2} Exactly 2 times
    
    T matches the character T literally (case sensitive)
    \d{2} match a digit [0-9]
    
        Quantifier: {2} Exactly 2 times
    
    (?::\d{2}){2} Non-capturing group
    
        Quantifier: {2} Exactly 2 times
        : matches the character : literally
        \d{2} match a digit [0-9]
            Quantifier: {2} Exactly 2 times
    
  4. # 4 楼答案

    首先了解正则表达式是如何工作的,这样格式就变得非常简单,下面是使用正则表达式的答案

    \d{4}\-\d{2}\-\d{2}T\d{2}:\d{2}:\d{2}

    Here is the Explanation:

    \在许多编程语言和java中用作转义序列。 d表示十进制整数

    阅读一些格式化数字打印输出的内容,这将有助于您理解模式规范

    https://docs.oracle.com/javase/tutorial/java/data/numberformat.html

  5. # 5 楼答案

    注意前面的简单答案,因为他们甚至接受像2016-75-92T40:25:82这样没有任何约束的东西,你需要单独执行它们

    举个例子,它匹配任何4位数的年份,从01个月到12个月

    \d{4}-(0[1-9]|1[0-2])
    

    但是限制天数会很痛苦