首页 > 编程语言 > 详细

Java正则表达式(1)

时间:2016-03-07 22:30:32      阅读:213      评论:0      收藏:0      [点我收藏+]

String类的三个内建正则表达式工具:

1.matches()方法

示例:检查一个句子是否以大写字母开头,以句号结尾 

1     public static boolean checkFormat(String sentence){
2         return sentence.matches("^[A-Z].+\\.$");
3     }

2.split()方法

示例:以空格分割knights字符串并以数组形式返回

1     public static void test(){
2         String knights = 
3                 "Then, when you have found the shrubbery,"
4                 + "you must cut down the mightiest tree in the forest... "
5                 + "with... a herring";
6         String newString = Arrays.toString(knights.split(" "));
7         System.out.println(newString);
8     }

3.replaceFirst()和replaceAll()方法

示例:替换knights字符串中所有元音字母为下划线

1     public static void test(){
2         String knights = 
3                 "Then, when you have found the shrubbery,"
4                 + "you must cut down the mightiest tree in the forest... "
5                 + "with... a herring";
6         String newKnights = knights.replaceAll("[AaEeIiOoUu]", "_");
7         System.out.println(newKnights);
8     }

replaceFirst()方法只在首次出现时替换,replaceAll则替换所有满足条件的部分

 

Java正则表达式(1)

原文:http://www.cnblogs.com/lamulacuo/p/RegExp1.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!