Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex for finding dates in a string

Tags:

java

regex

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. Any help is appreciated thanks in advance.

like image 846
newtoprogramming Avatar asked Feb 14 '26 05:02

newtoprogramming


2 Answers

Your pattern does not allow for single-digit days and months. Make the leading 0 optional:

^(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
like image 151
Martin Ender Avatar answered Feb 15 '26 19:02

Martin Ender


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$");
like image 29
MansoorShaikh Avatar answered Feb 15 '26 20:02

MansoorShaikh