简体   繁体   English

文本是否包含日期格式?

[英]Does text contain date format?

Suppose I have this text:假设我有这样的文字:

how are you? ok, I'm fine and how are you 08-01-20. Nice.

How to check if it contains substring in a specific format?如何检查它是否包含特定格式的子字符串? In this case this is a date format: dd-MM-yy在这种情况下,这是一种日期格式: dd-MM-yy

 how are you? ok, I'm fine and how are you 08-01-20. Nice.  

This case must return 08-01-20 .这种情况必须返回08-01-20

But this text:但是这段文字:

 how are you? ok, I'm fine and how are you 18:01:21. Nice.

must return null .必须返回null

So I need method that return 08-01-20 in first case and return null in second case.所以我需要在第一种情况下返回08-01-20并在第二种情况下返回null 的方法

You can use match with regex .*?\\d{2}-\\d{2}-\\d{2}.* like so :您可以将匹配与正则表达式.*?\\d{2}-\\d{2}-\\d{2}.*如下所示:

".*?\\d{2}-\\d{2}-\\d{2}.*".toRegex().matches(str)

Edit编辑

After OP edit, You can extract the date with the previews regex, then use a formatter to check if the date is valid or not, if yes return it, else return null : 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;
    }
}

Check kotlin demo检查kotlin 演示

Or if you want to get the same value and not a LocalDate you can return the extracted date as a String like so :或者,如果您想获得相同的值而不是 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;
    }
}

Note: in the second part I changed the regex and I used boundaries to avoid some case like 321-12-4321注意:在第二部分中,我更改了正则表达式并使用边界来避免某些情况,例如321-12-4321

Edit编辑

@Andreas put a good point in comment, so if you have many dates with that format, and at least one of them is valid, in this case you have to loop over all the matches and check one by one like so : @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
}

This will return the first valid date in your date这将返回您日期中的第一个有效日期

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM