简体   繁体   English

用于在字符串中查找日期的正则表达式

[英]Regex for finding dates in a string

Hello people thanks for the help so far. 大家好,感谢您的帮助。 I Have a regex for finding a date in a given string and it does not seem to working. 我有一个正则表达式,用于在给定字符串中查找日期,但它似乎无法正常工作。 Could someone tell me what I am doing wrong? 有人能告诉我我做错了什么吗? The code goes something like 代码类似于

Pattern pattern = Pattern.compile("^(0[1-9]|[12][0-9]|3[01])[- /.](0[1-9]|1[012])[- /.](19|20)\\d\\d(?:,)$");
Matcher match = pattern.matcher(text1);

List<String> removable1 = new ArrayList<String>();             
while(match.find()) {
    removable1.add(match.group());
}

I know that there is a date "7/2/2013" contained in the string text1 which is not being written to the list removable1. 我知道字符串text1中包含一个日期“7/2/2013”​​,该日期未写入可删除列表1。 Any help is appreciated thanks in advance. 任何帮助表示感谢提前。

Your pattern does not allow for single-digit days and months. 您的模式不允许使用一位数的日期和月份。 Make the leading 0 optional: 使前导0可选:

^(0?[1-9]|[12][0-9]|3[01])[- /.](0?[1-9]|1[012])[- /.](19|20)\\d\\d(?:,)$

Also, I'm not sure what the trailing comma does. 另外,我不确定尾随的逗号是做什么的。 And additionally, you say "contained in the string", but ^ and $ anchor the pattern to the start and end. 另外,你说“包含在字符串中”,但^$将模式锚定到开头和结尾。 So you might want to remove these, if you want to find dates: 因此,如果要查找日期,可能需要删除它们:

(0?[1-9]|[12][0-9]|3[01])[- /.](0?[1-9]|1[012])[- /.](19|20)\\d\\d

Finally, if you want to make sure that both date separators are the same character, you can do this: 最后,如果要确保两个日期分隔符都是相同的字符,则可以执行以下操作:

(0?[1-9]|[12][0-9]|3[01])([- /.])(0?[1-9]|1[012])\\2(19|20)\\d\\d

Finally, for some optimization, avoid capturing where you don't need it (and potentially make the century optional: 最后,对于某些优化,避免捕获不需要它的地方(并且可能使世纪可选:

(?:0?[1-9]|[12][0-9]|3[01])([- /.])(?:0?[1-9]|1[012])\\1(?:19|20)?\\d\\d

Try this 试试这个

String text1="07/02/2013";
Pattern pattern = Pattern.compile("^(0[1-9]|[12][0-9]|3[01])[- /.](0[1-9]|1[012])[- /.](19|20)\\d\\d$");

regex you used is not correct. 你使用的正则表达式是不正确的。 Task section to match day for example 例如,匹配日的任务部分

0[1-9]|[12][0-9]|3[01])

This regex means 0 should be used as prefix if day is 1~9. 如果day为1~9,则此正则表达式表示0应该用作前缀。

To fix this issue , you should add ? 要解决此问题,您应该添加? which means preceding item is optional. 这意味着前一项是可选的。 So you can change your regex string to 所以你可以改变你的正则表达式字符串

(0?[1-9]|[12][0-9]|3[01])[- /.](0?[1-9]|1[012])[- /.](19|20)\d\d

In future, you can use regular expression tester to debug those issues. 将来,您可以使用正则表达式测试程序来调试这些问题。 They are useful and helps to save time. 它们很有用,有助于节省时间。 For example, http://regex.uttool.com , http://regexpal.com/ 例如, http ://regex.uttool.com,http://regexpal.com/

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

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