Programming 课程第八周的课堂练习
本周主要练习使用正则表达式进行匹配。
- final 关键字
- Pattern 类
- compile() 方法
- matcher() 方法
- CASE_INSENSITIVE 常量
- Matcher 类
- find() 方法
- group() 方法
- groupCount() 方法
| import java.util.regex.Matcher; |
| import java.util.regex.Pattern; |
| |
| public class practice1 { |
| public static void main(String []args) |
| { |
| final String regex="s"; |
| final String string="First Semester Students"; |
| |
| final Pattern pattern=Pattern.compile(regex,Pattern.CASE_INSENSITIVE); |
| final Matcher matcher=pattern.matcher(string); |
| |
| while(matcher.find()) |
| { |
| System.out.println("Full match:"+matcher.group()); |
| |
| for(int i=1;i<=matcher.groupCount();i++) |
| { |
| System.out.println("Group" + i +":"+matcher.group(i)); |
| } |
| } |
| } |
| } |
| |
| import java.util.regex.Matcher; |
| import java.util.regex.Pattern; |
| |
| public class practice2 { |
| public static void main(String []args) |
| { |
| final String regex="s."; |
| final String string="First Semester Students"; |
| |
| final Pattern pattern=Pattern.compile(regex,Pattern.CASE_INSENSITIVE); |
| final Matcher matcher=pattern.matcher(string); |
| |
| while(matcher.find()) |
| { |
| System.out.println("Full match:"+matcher.group(0)); |
| |
| for(int i=1;i<=matcher.groupCount();i++){ |
| System.out.println("Group"+i+":"+matcher.group(i)); |
| } |
| } |
| } |
| } |
| |
| import java.util.regex.Matcher; |
| import java.util.regex.Pattern; |
| |
| public class practice3 { |
| public static void main(String []args) |
| { |
| final String regex="a{3,6}"; |
| final String string="a aa aaa aaaa aaaaaaaaaa"; |
| |
| final Pattern pattern=Pattern.compile(regex); |
| final Matcher matcher=pattern.matcher(string); |
| |
| while(matcher.find()) |
| { |
| System.out.println("Full match:"+matcher.group(0)); |
| |
| for(int i=1;i<matcher.groupCount();i++) |
| { |
| System.out.print("Group"+i+":"+matcher.group(i)); |
| } |
| } |
| } |
| } |
| |
| import java.util.regex.Matcher; |
| import java.util.regex.Pattern; |
| |
| public class practice4 { |
| public static void main(String []args) |
| { |
| final String regex="([a-z]{1,10})"; |
| final String string="abc123DEF this is for lab practice"; |
| |
| final Pattern pattern=Pattern.compile(regex,Pattern.CASE_INSENSITIVE); |
| final Matcher matcher=pattern.matcher(string); |
| |
| while(matcher.find()) |
| { |
| System.out.println("Full match:"+matcher.group(0)); |
| |
| for(int i=0;i<matcher.groupCount();i++) |
| { |
| System.out.println("Group "+i+" : "+matcher.group(i)); |
| } |
| } |
| } |
| } |