返回
正则表达式教程:12小时制时间(hh:mm:ss)
正则表达式
2024-02-28 15:55:38
一、正则解释
正则表达式:/^(?:1[0-2]|0?[1-9]):[0-5]\d:[0-5]\d$/
- ^ : 匹配字符串开头。
- (?:1[0-2]|0?[1-9]) : 匹配小时部分,范围为 1:00 到 12:59。
- : : 匹配分隔符冒号。
- [0-5]\d : 匹配分钟部分,范围为 00 到 59。
- : : 匹配分隔符冒号。
- [0-5]\d : 匹配秒钟部分,范围为 00 到 59。
- $ : 匹配字符串结尾。
二、使用场景
- 验证用户输入的 12 小时制时间格式。
- 从文本中提取 12 小时制时间戳。
- 比较和排序 12 小时制时间。
- 将 12 小时制时间转换为其他时间格式。
三、代码示例
JavaScript
const regex = /^(?:1[0-2]|0?[1-9]):[0-5]\d:[0-5]\d$/;
const testString = '11:34:55';
console.log(regex.test(testString)); // true
Java
import java.util.regex.Pattern;
import java.util.regex.Matcher;
public class TimeMatcher {
public static void main(String[] args) {
String regex = "^(?:1[0-2]|0?[1-9]):[0-5]\\d:[0-5]\\dimport java.util.regex.Pattern;
import java.util.regex.Matcher;
public class TimeMatcher {
public static void main(String[] args) {
String regex = "^(?:1[0-2]|0?[1-9]):[0-5]\\d:[0-5]\\d$";
String testString = "11:34:55";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(testString);
System.out.println(matcher.matches()); // true
}
}
quot;;
String testString = "11:34:55";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(testString);
System.out.println(matcher.matches()); // true
}
}
PHP
<?php
$regex = '/^(?:1[0-2]|0?[1-9]):[0-5]\d:[0-5]\d$/';
$testString = '11:34:55';
echo preg_match($regex, $testString); // 1
?>
Python
import re
regex = "^(?:1[0-2]|0?[1-9]):[0-5]\d:[0-5]\dimport re
regex = "^(?:1[0-2]|0?[1-9]):[0-5]\d:[0-5]\d$"
testString = "11:34:55"
match = re.search(regex, testString)
print(match) # <re.Match object; span=(0, 8), match='11:34:55'>
quot;
testString = "11:34:55"
match = re.search(regex, testString)
print(match) # <re.Match object; span=(0, 8), match='11:34:55'>