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

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])

commented: Excellent explanation of Regular Expressions +2
commented: Great explanation with examples :) +3
commented: regex is a pain in the but good descrip. +7

thanks :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.