如何从字符串中仅提取表格XX:YY的时间部分?
例如 - 来自如下字符串:
sdhgjhdgsjdf12:34knvxjkvndf ,我只想提取 12:34 。
(周围的字符当然也可以是空格)
当然我可以找到分号,然后获得两个字符,之后有两个字符,但它是bahhhhhh .....
谢谢!
答案 0 :(得分:4)
您可以使用这种基于环视的正则表达式来匹配:
(?<!\d)\d{2}:\d{2}(?!\d)
在Java中:
Pattern p = Pattern.compile("(?<!\\d)\\d{2}:\\d{2}(?!\\d)");
RegEx分手:
(?<!\d) # negative lookbehind to assert previous char is not a digit
\d{2} # match exact 2 digits
: # match a colon
\d{2} # match exact 2 digits
(?!\d) # negative lookahead to assert next char is not a digit
完整代码:
Pattern p = Pattern.compile("(?<!\\d)\\d{2}:\\d{2}(?!\\d)");
Matcher m = pattern.matcher(inputString);
if (m.find()) {
System.err.println("Time: " + m.group());
}