1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96
| import java.util.regex.Matcher; import java.util.regex.Pattern;
public class RegExDemo { public static void main(String[] args) { String content = "this is a test"; String pattern1 = ".*is\\s+.*"; String pattern2 = "\\s"; String pattern3 = "is"; boolean isMatch = Pattern.matches(pattern1, content); System.out.println(isMatch); Pattern p1 = Pattern.compile(pattern1); Pattern p2 = Pattern.compile(pattern2); Pattern p3 = Pattern.compile(pattern3); String[] fields = p2.split(content); for(String s : fields) { System.out.println(s); } Matcher m1 = p1.matcher(content); Matcher m2 = p2.matcher(content); Matcher m3 = p3.matcher(content); isMatch = m1.matches(); System.out.println(isMatch); isMatch = m2.matches(); System.out.println(isMatch); isMatch = m3.find(); System.out.println(isMatch); System.out.println(m3.start() + ", " + m3.end() + ", " + m3.group());
Pattern pg = Pattern.compile("([a-z]+)(\\s+)"); Matcher mg = pg.matcher(content); mg.find(); for(int i = 1; i <= mg.groupCount(); ++i) { System.out.println(mg.start(i) + ", " + mg.end(i) + ", " + mg.group(i)); } } }
|