|
C:\AAA_Webcrawler\webcrawler\src\ch\jai\java\example\Pattern_Example.java
|
1 package ch.jai.java.example;
2
3 import junit.framework.TestCase;
4
5 import java.util.regex.Pattern;
6
7 /**
8 * Pattern Example
9 *
10 * @author www.jai.ch
11 */
12 public class Pattern_Example extends TestCase {
13 /**
14 *
15 */
16 public void test_match_simple() {
17
18 // match for : whitespace characters
19 String regex = "\\s+";
20 assertTrue(" \t\n".matches(regex));
21 assertFalse("a".matches(regex));
22
23 // match for : non-whitespace characters
24 regex = "\\S+";
25 assertTrue( "abc.123".matches(regex));
26 assertFalse( "abc 123".matches(regex));
27
28 // match for : 2 or more non-whitespace characters
29 regex = "\\S{2,}";
30 assertTrue( "ab".matches(regex));
31 assertTrue( "abc".matches(regex));
32 assertFalse( "a".matches(regex));
33
34 // match for : 2 or 3 non-whitespace characters
35 regex = "\\S{2,3}";
36 assertTrue( "ab".matches(regex));
37 assertTrue( "abc".matches(regex));
38 assertFalse( "abcd".matches(regex));
39 }
40 /**
41 *
42 */
43 public void test_match_numbers() {
44
45 // d : A digit: [0-9]
46 String regex = "\\d+";
47 assertTrue( "123".matches(regex));
48 assertFalse( "a".matches(regex));
49
50 // d : A digit: [0-9]
51 regex = "first a string then the numer \\d+";
52 assertTrue( "first a string then the numer 123456".matches(regex));
53 assertFalse( "first a string then the numer one".matches(regex));
54 }
55 /**
56 *
57 */
58 public void test_match_email() {
59
60 final String emailRegEx = "\\S+@\\S{2,}\\.\\S{2,3}";
61
62 // correct email strings
63 final boolean matches = Pattern.matches(emailRegEx, "info@jai.ch");
64 assertTrue( matches);
65
66 // same result from String class
67 assertTrue( "info@jai.ch".matches(emailRegEx));
68 assertTrue( "firstname.lastname@javasoft.com".matches(emailRegEx));
69
70 // incorrect email strings
71 assertFalse( "i nfo@jai.ch".matches(emailRegEx));
72 assertFalse( "info@jai ch".matches(emailRegEx));
73 assertFalse( "info jai.ch".matches(emailRegEx));
74 assertFalse( "@jai.ch".matches(emailRegEx));
75 assertFalse( "info@jaich".matches(emailRegEx));
76 assertFalse( "".matches(emailRegEx));
77 assertFalse( "info@jai:ch".matches(emailRegEx));
78 assertFalse( "boda@jai.c".matches(emailRegEx));
79 }
80 }
81