📌  相关文章
📜  如何使用正则表达式以 24 小时格式验证时间

📅  最后修改于: 2021-09-06 11:25:21             🧑  作者: Mango

给定一个字符串str ,任务是使用正则表达式检查字符串是否为 24 小时格式的有效时间。

例子:

方法:这个问题可以通过使用正则表达式来解决。

  1. 获取字符串。
  2. 创建一个正则表达式来检查 24 小时格式的时间,如下所述:
regex = "([01]?[0-9]|2[0-3]):[0-5][0-9]";
  1. 在哪里:
    • (代表组的开始。
    • [01]?[0-9]表示时间以0-9、1-9、00-09、10-19开始。
    • |代表或。
    • 2[0-3]代表时间从20-23开始。
    • )代表组的结束。
    • :表示时间后面应该跟一个冒号(:)。
    • [0-5][0-9]表示时间后跟00到59
  2. 将给定的字符串与正则表达式匹配,在Java这可以通过使用 Pattern.matcher() 来完成。
  3. 如果字符串与给定的正则表达式匹配,则返回 true,否则返回 false。

下面是上述方法的实现:

C++
// C++ program to validate
// time in 24-hour format
// using Regular Expression
#include 
#include 
using namespace std;
 
// Function to validate time in 24-hour format
bool isValidTime(string str)
{
 
  // Regex to check valid time in 24-hour format
  const regex pattern("([01]?[0-9]|2[0-3]):[0-5][0-9]");
 
  // If the time in 24-hour format
  // is empty return false
  if (str.empty())
  {
     return false;
  }
 
  // Return true if the time in 24-hour format
  // matched the ReGex
  if(regex_match(str, pattern))
  {
    return true;
  }
  else
  {
    return false;
  }
}
 
// Driver Code
int main()
{
   
  // Test Case 1:
  string str1 = "13:05";
  cout << str1 + ": "<< isValidTime(str1) << endl;
 
  // Test Case 2:
  string str2 = "02:15";
  cout << str2 + ": "<< isValidTime(str2) << endl;
 
  // Test Case 3:
  string str3 = "24:00";
  cout << str3 + ": "<< isValidTime(str3) << endl;
 
  // Test Case 4:
  string str4 = "10:60";
  cout << str4 + ": "<< isValidTime(str4) << endl;
 
  // Test Case 5:
  string str5 = "10:15 PM";
  cout << str5 + ": "<< isValidTime(str5) << endl;
 
  return 0;
}
 
// This code is contributed by yuvraj_chandra


Java
// Java program to validate the time in
// 24-hour format using Regular Expression.
 
import java.util.regex.*;
 
class GFG {
 
    // Function to validate the time in 24-hour format
    public static boolean isValidTime(String time)
    {
 
        // Regex to check valid time in 24-hour format.
        String regex = "([01]?[0-9]|2[0-3]):[0-5][0-9]";
 
        // Compile the ReGex
        Pattern p = Pattern.compile(regex);
 
        // If the time is empty
        // return false
        if (time == null) {
            return false;
        }
 
        // Pattern class contains matcher() method
        // to find matching between given time
        // and regular expression.
        Matcher m = p.matcher(time);
 
        // Return if the time
        // matched the ReGex
        return m.matches();
    }
 
    // Driver Code.
    public static void main(String args[])
    {
 
        // Test Case 1:
        String str1 = "13:05";
        System.out.println(str1 + ": "
                           + isValidTime(str1));
 
        // Test Case 2:
        String str2 = "02:15";
        System.out.println(str2 + ": "
                           + isValidTime(str2));
 
        // Test Case 3:
        String str3 = "24:00";
        System.out.println(str3 + ": "
                           + isValidTime(str3));
 
        // Test Case 4:
        String str4 = "10:60";
        System.out.println(str4 + ": "
                           + isValidTime(str4));
 
        // Test Case 5:
        String str5 = "10:15 PM";
        System.out.println(str5 + ": "
                           + isValidTime(str5));
    }
}


Python3
# Python3 program to validate the time in
# 24-hour format using Regular Expression.
import re
 
# Function to validate the time
# in 24-hour format
def isValidTime(time):
     
    # Regex to check valid time in 24-hour format.
    regex = "^([01]?[0-9]|2[0-3]):[0-5][0-9]$";
 
    # Compile the ReGex
    p = re.compile(regex);
 
    # If the time is empty
    # return false
    if (time == "") :
        return False;
         
    # Pattern class contains matcher() method
    # to find matching between given time
    # and regular expression.
    m = re.search(p, time);
     
    # Return True if the time
    # matched the ReGex otherwise False
    if m is None :
        return False;
    else :
        return True
         
# Driver Code.
if __name__ == "__main__" :
     
    # Test Case 1:
    str1 = "13:05";
    print(str1, ": ", isValidTime(str1));
 
    # Test Case 2:
    str2 = "02:15";
    print(str2, ": ", isValidTime(str2));
     
    # Test Case 3:
    str3 = "24:00";
    print(str3, ": ", isValidTime(str3));
     
    # Test Case 4:
    str4 = "10:60";
    print(str4, ": ", isValidTime(str4));
     
    # Test Case 5:
    str5 = "10:15 PM";
    print(str5, ": ", isValidTime(str5));
 
# This code is contributed by AnkitRai01


输出:
13:05: true
02:15: true
24:00: false
10:60: false
10:15 PM: false

如果您想与行业专家一起参加直播课程,请参阅Geeks Classes Live