954,545 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

can anyone please expalain a piece in this code?

1 // Fig. 29.24: RegexMatches.java
2 / Demonstrating Classes Pattern and Matcher.
3 import java.util.regex.Matcher;
4 import java.util.regex.Pattern;
5
6 public class RegexMatches
7 {
8 public static void main( String args[] )
9 {
10 // create regular expression
11 Pattern expression =
12 Pattern.compile( "J.*\\d[0-35-9]-
\\d\\d-\\d\\d" );
13
14 String string1 =
"Jane's Birthday is 05-12-75\n" +
15 "Dave's Birthday is 11-04-68\n" +
16 "John's Birthday is 04-28-73\n" +
17 "Joe's Birthday is 12-17-77";
18
19 // match regular expression to string and
print matches
20 Matcher matcher = expression.matcher(
string1 );
21
22 while ( matcher.find() )
23 System.out.println( matcher.group() );
24 } // end main
25 } // end class RegexMatches

I know what the code does...it matches a birthday in a given regular expression...what i just dont understand is line 12. what does the "[0-35-9]" in this line mean? thanks guys

herms14
Light Poster
47 posts since Mar 2008
Reputation Points: 10
Solved Threads: 0
 

Well, this question has more to do with regular expressions than Java... Anyways I'll try to define what the Regex "J.*\\d[0-35-9]-\\d\\d-\\d\\d" means.

.* will match any number of any characters, \\d matches any digit, so the expression will match any string that has a J followed by anything (matched by J.*)
followed by a single digit (matched by \\d),
followed by another digit, which is between 0 and 3 or 5 and 9 (that is any digit except 4) (matched by [0-35-9]
(You should ask the reason is behind this kind of matching to the author of the program :confused: )
followed by a '-' followed by two digits, another '-' and two digits. (\d\d-\d\d)

So this regex matches
"Jane's Birthday is 05-12-75\n"
and "Joe's Birthday is 12-17-77"

But it doesn't match: "Dave's Birthday is 11-04-68\n" (No match for the J.*)
or "John's Birthday is 04-28-73\n" (No match for [0-3][5-9])

vicky_dev
Junior Poster in Training
86 posts since May 2005
Reputation Points: 28
Solved Threads: 2
 

thanks :)

herms14
Light Poster
47 posts since Mar 2008
Reputation Points: 10
Solved Threads: 0
 

This question has already been solved

Post: Markdown Syntax: Formatting Help
You