This is some information on the Java 6 certification that I prepare. This information is not very well structured and it is most of the time an answer to the questions that come when I read the SCJP 6 book (Bates and Sierra). *** AS OF 5 OF MARCH 2010, I AM SCJP 6.0 ***

Tuesday, January 12, 2010

14 - RegExp

import java.util.regex.*;
class Regex2 {
    public static void main(String[] args) {
        Pattern p = Pattern.compile(args[0]);
        Matcher m = p.matcher(args[1]);
        boolean b = false;
        while(b = m.find()) {
             System.out.print(m.start() + m.group());
        }
    }
}

1) simple

F:\SCP\CHAP6>java Regex2 "ab" "abaaaba"
0 ab
4 ab

2)

F:\SCP\CHAP6>java Regex2 "aba" "ababab"
0 aba

3) meta d : a digit

F:\SCP\CHAP6>java Regex2 "\d" "a12c3e456f"
1 1
2 2
4 3
6 4
7 5
8 6

4) meta w : a word character (letters, digits or "_")

F:\SCP\CHAP6>java Regex2 "\w" "a 1 56 _Z"
0 a
2 1
4 5
5 6
7 _
8 Z

5) 1 char !

F:\SCP\CHAP6>java Regex2 [a-cA-C] cafeBABE
0 c
1 a
4 B
5 A
6 B

6) no +

F:\SCP\CHAP6>java Regex2 "0[xX][0-9a-fA-F]" "12 0x 0x12 0Xf 0xg"
6 0x1
11 0Xf

7) +

F:\SCP\CHAP6>java Regex2 "0[xX][0-9a-fA-F]+" "12 0x 0x12 0Xf 0xg"
6 0x12
11 0Xf

8a) a digit !

F:\SCP\CHAP6>java Regex2 "\d" "1 a12 234b"
0 1
3 1
4 2
6 2
7 3
8 4

8b) a digit and a + !

F:\SCP\CHAP6>java Regex2 "\d+" "1 a12 234b"
0 1
3 12
6 234

9) parenthesis and +

F:\SCP\CHAP6>java Regex2 "0[xX]([0-9a-fA-F])+" "12 0x 0x12 0Xf 0xg 0XFAAAAA"
6 0x12
11 0Xf
19 0XFAAAAA

10) give me proj1 followed by something that is NOT a "," zero or several times

F:\SCP\CHAP6>java Regex2 "proj1[^,]*" proj3.txt,proj1sched.pdf,proj1,proj2,proj1
.java
10 proj1sched.pdf
25 proj1
37 proj1.java

11) \s is a white space

? is zero or 1
+ 1 or more
give me 3 digits followed by zero or 1 "-" or zero or 1 space followed by 4 digits

F:\SCP\CHAP6>java Regex2 "\d\d\d([-\s])?\d\d\d\d" 1234567
0 1234567

F:\SCP\CHAP6>java Regex2 "\d\d\d([-\s])?\d\d\d\d" "123 4567"
0 123 4567

F:\SCP\CHAP6>java Regex2 "\d\d\d([-\s])?\d\d\d\d" "123-4567"
0 123-4567

12) . dot is any character

the following can produce

F:\SCP\CHAP6>java Regex2 "a.c" "ac abc a c"
3 abc
7 a c

13)
greedy


F:\SCP\CHAP6>java Regex2 ".*xx" "yyxxxyxx"
0 yyxxxyxx

reluctant
F:\SCP\CHAP6>java Regex2 ".*?xx" "yyxxxyxx"
0 yyxx
4 xyxx

14) \n \b \t

15)

F:\SCP\CHAP6>java Regex2 "\d" a1b2c3d44
1 1
3 2
5 3
7 4
8 4

F:\SCP\CHAP6>java Regex2 "\d+" a1b2c3d44
1 1
3 2
5 3
7 44

F:\SCP\CHAP6>java Regex2 "\d*" a1b2c3d44
0
1 1
2
3 2
4
5 3
6
7 44
9

No comments:

Post a Comment

Followers