假设我有这样的文字:
how are you? ok, I'm fine and how are you 08-01-20. Nice.
如何检查它是否包含特定格式的子字符串?在本例中,这是日期格式:dd-MM-yy
how are you? ok, I'm fine and how are you 08-01-20. Nice.
此案例必须返回 08-01-20
。
但是这段文字:
how are you? ok, I'm fine and how are you 18:01:21. Nice.
必须返回null。
所以我需要在第一种情况下返回 08-01-20
并在第二种情况下返回 null 的方法。
最佳答案
您可以使用正则表达式 .*?\d{2}-\d{2}-\d{2}.*
进行匹配像这样:
".*?\\d{2}-\\d{2}-\\d{2}.*".toRegex().matches(str)
<小时/>
编辑
OP编辑后,您可以使用预览正则表达式提取日期,然后使用格式化程序检查日期是否有效,如果有效则返回它,否则返回null:
fun check(str: String): LocalDate? {
var formatter = DateTimeFormatter.ofPattern("dd-MM-yy");
var v = str.replace(".*?(\\b\\d{2}-\\d{2}-\\d{2}\\b).*".toRegex(), "$1");
try{
return LocalDate.parse(v, formatter);
}catch(e: DateTimeParseException) {
return null;
}
}
或者,如果您想获得相同的值而不是 LocalDate,您可以将提取的日期作为字符串返回,如下所示:
fun check(str: String): String? {
var formatter = DateTimeFormatter.ofPattern("dd-MM-yy");
var v = str.replace(".*?(\\b\\d{2}-\\d{2}-\\d{2}\\b).*".toRegex(), "$1");
try{
LocalDate.parse(v, formatter);
return v;
}catch(e: DateTimeParseException) {
return null;
}
}
注意:在第二部分中,我更改了正则表达式,并使用边界来避免像 321-12-4321
这样的情况。
编辑
@Andreas 在评论中提出了一个很好的观点,因此,如果您有许多采用该格式的日期,并且至少其中一个有效,在这种情况下,您必须循环所有匹配项并逐一检查,如下所示:
fun check(str: String): LocalDate? {
var formatter = DateTimeFormatter.ofPattern("dd-MM-yy")
val regex = Regex("\\b\\d{2}-\\d{2}-\\d{2}\\b")
for (match in regex.findAll(str)) {
try{
return LocalDate.parse(match.value, formatter);
}catch(e: DateTimeParseException) { }
}
return null
}
这将返回您的日期中的第一个有效日期
关于java - 文本是否包含日期格式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59734803/