regular expression problem
Hello
I'm trying to decode a time/date string using regular expressions. Right now the code I have in there is very rigid and I'm trying to use regular expresions to make it more flexible. I haven't used them before so I'm learning as I go. Right now, I'm just trying to make an expresion able to parse the existing (rigid) incoming string.
Expecting a string s of format ddHHMMZ month yy
For example 132210Z April 05
What I'm doing
String patternstring ="([0-3]?\\d)([12]?\\d)([0-5]\\d)([Z]?).(\\w).(\\d\\d)";
Pattern pattern = Pattern.compile(patternstring, Pattern.CASE_INSENSITIVE);
Matcher match = pattern.matcher(s);
String day = matcher.group(2);
String hour = matcher.group(3);
....etc...
However the program throws an exception while executing String day = matcher.group(2);
complaining about IlegalStateException, which I looked up in the API and it says that it means it found no match. So... I'm guessign somethign about my patternstring is not right for that kind of input. What am I doing wrong here?
Thanks.
[1141 byte] By [
zkajana] at [2007-11-26 17:09:26]

A small modifiecation -
String s = "132210Z April 05";
String patternstring = "([0-3]?\\d)([12]?\\d)([0-5]\\d)([Z]?).(\\w).(\\d\\d)";
Pattern pattern = Pattern.compile(patternstring, Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(s);
if (matcher.matches())
{
String day = matcher.group(2);
String hour = matcher.group(3);
}
Until you call matches() the regex is not applied.
> Oh thank you. Now I feel like a dunce.
Your pattern is also wrong! You need something likeString patternstring = "([0-3][0-9])([12][0-9])([0-5][0-9])(Z?)\\s+(\\w+)\\s+(\\d\\d)";
or better stillString patternstring = "(0[1-9]|[1-2][0-9]|3[0-1])(0[1-9]|1[0-9]|2[0-3])(0[1-9]|1[0-2])(Z?)\\s+(\\w+)\\s+(\\d\\d)";
Message was edited by:
sabre150
> Are you trying to [i]validate[/i] the date, or just
> break it down? Assuming it's the latter, you can
> probably just use [code]
> "(\\d\\d)(\\d\\d)(\\d\\d)[Zz]?\\s+(\\w+)\\s+(\\d\\d)"
> /code]
As normal, uncle_alice, you are right! My muddled thinking was mixing the validation and extraction aspects so making my regex unnecessarily complex.