zoukankan      html  css  js  c++  java
  • Java编程思想学习(十) 正则表达式

    正则表达式是一种强大的文本处理工具,使用正则表达式我们可以以编程的方法,构造复杂的文本模式,并且对输入的字符串进行搜索.在我看来,所谓正则表达式就是我们自己定义一些规则,然后就可以验证输入的字符串是不是满足这些规则,主要的问题在于定义这些规则时要用到一些比较特别的语法,加大了理解的难度.以前就学习过一次java的正则表达式,但是学的模模糊糊的;主要的原因在于正则表达式的语法实在是很复杂,所以这次又去学习了正则的基本语法.其实在了解了正则表达式的基本语法后,学习java中的正则表达式还是很简单的.下面先介绍正则表达式的基本语法,然后再是java中的两种调用正则表示式的方式.

    一.正则表达式的基本语法(内容转自网络) 
    两个特殊的符号’^’和’$’。他们的作用是分别指出一个字符串的开始和结束。例子如下:

    “^The”:表示所有以”The”开始的字符串(”There”,”The cat”等); 
    “of despair$”:表示所以以”of despair”结尾的字符串;

    “^abc$”:表示开始和结尾都是”abc”的字符串——呵呵,只有”abc”自己了; 
    “notice”:表示任何包含”notice”的字符串。

    象最后那个例子,如果你不使用两个特殊字符,你就在表示要查找的串在被查找串的任意部分——你并 
    不把它定位在某一个顶端。

    其它还有’*’,’+’和’?’这三个符号,表示一个或一序列字符重复出现的次数。它们分别表示“没有或 
    更多”,“一次或更多”还有“没有或一次”。下面是几个例子:

    “ab*”:表示一个字符串有一个a后面跟着零个或若干个b。(”a”, “ab”, “abbb”,……); 
    “ab+”:表示一个字符串有一个a后面跟着至少一个b或者更多; 
    “ab?”:表示一个字符串有一个a后面跟着零个或者一个b; 
    “a?b+$”:表示在字符串的末尾有零个或一个a跟着一个或几个b。

    你也可以使用范围,用大括号括起,用以表示重复次数的范围。

    “ab{2}”:表示一个字符串有一个a跟着2个b(”abb”); 
    “ab{2,}”:表示一个字符串有一个a跟着至少2个b; 
    “ab{3,5}”:表示一个字符串有一个a跟着3到5个b。

    请注意,你必须指定范围的下限(如:”{0,2}”而不是”{,2}”)。还有,你可能注意到了,’*’,’+’和 
    ‘?’相当于”{0,}”,”{1,}”和”{0,1}”。 
    还有一个’¦’,表示“或”操作:

    “hi¦hello”:表示一个字符串里有”hi”或者”hello”; 
    “(b¦cd)ef”:表示”bef”或”cdef”; 
    “(a¦b)*c”:表示一串”a”“b”混合的字符串后面跟一个”c”;

    ‘.’可以替代任何字符:

    “a.[0-9]”:表示一个字符串有一个”a”后面跟着一个任意字符和一个数字; 
    “^.{3}$”:表示有任意三个字符的字符串(长度为3个字符);

    方括号表示某些字符允许在一个字符串中的某一特定位置出现:

    “[ab]”:表示一个字符串有一个”a”或”b”(相当于”a¦b”); 
    “[a-d]”:表示一个字符串包含小写的’a’到’d’中的一个(相当于”a¦b¦c¦d”或者”[abcd]”); 
    “^[a-zA-Z]”:表示一个以字母开头的字符串; 
    “[0-9]%”:表示一个百分号前有一位的数字; 
    “,[a-zA-Z0-9]$”:表示一个字符串以一个逗号后面跟着一个字母或数字结束。

    你也可以在方括号里用’^’表示不希望出现的字符,’^’应在方括号里的第一位。(如:”%[^a-zA-Z]%”表 
    示两个百分号中不应该出现字母)。

    为了逐字表达,你必须在”^.$()¦*+?{”这些字符前加上转移字符’’。 
    请注意在方括号中,不需要转义字符。

    二.使用String自带的正则表达式 
    java的String类自带了一些正则表达式,我们可以通过一个String类对象很容易的使用正则表达式,具体如下: 
    (1)matches()方法,参数是我们传入的正则表达式,如果整个字符串匹配成功则返回true否则返回false.如下面的代码所示:

     1 public class IntegerMatch {
     2 
     3     public static void main(String[] args){
     4         ///匹配一个可能为负的整数
     5         System.out.println("-1234".matches("-?\d+"));
     6 
     7         //下面的情况是+与\d+匹配失败
     8         System.out.println("+5678".matches("-?\d+"));
     9 
    10         ///下面表达式表示可能一个加号或减号开头的整数
    11         //因为加号+有特殊意义,所以要用\进行转义
    12         System.out.println("+5678".matches("(-|\+)?\d+"));
    13     }/*Output
    14         true
    15         false
    16         true
    17     */
    18 }

    (2).split()方法,我们传入一个正则表达式,它根据这个表达式将字符串分割成几个部分,返回一个String对象数组.它还有一个重载版本,还允许我们传入一个整数控制分割成几部分.如下面代码所示:

     1 import java.util.Arrays;
     2 
     3 ///spllit()是String类自带的一个正则表达式工具
     4 ///其功能是:将字符串重正则表达式匹配的地方切开成为一个个单词
     5 ///其实就是指定分隔符将字符串分成许多个单词(分隔符会消失),返回String数组
     6 public class SplitTest {
     7 
     8     public static String knights="Then, when you have found the shrubbery, you must"
     9         +"cut dwon the mightiest tree forest..."+"with... a herring";
    10     public static void split(String regex){
    11         System.out.println(Arrays.toString(knights.split(regex)));
    12     }
    13 
    14     public static void main(String[] args){
    15         split(" "); //用空格作为分隔符
    16         split("\W+"); ///非字母字符作为分隔符
    17         split("n\W+");///以n和非字母字符作为分隔符
    18     }/*Output
    19           [Then,, when, you, have, found, the, shrubbery,, you, mustcut, dwon, the, mightiest, tree, forest...with..., a, herring]
    20           [Then, when, you, have, found, the, shrubbery, you, mustcut, dwon, the, mightiest, tree, forest, with, a, herring]
    21           [The, whe, you have found the shrubbery, you mustcut dwo, the mightiest tree forest...with... a herring]
    22     */
    23 }

    (3)最后一个是”替换”,包括replaceFirst(),和replaceAll()两个函数,都需要我们传入一个正则表达式.两个的不同在于第一个函数只替换正则表达式第一个匹配的子串,而第二个会替换所有匹配的子串.如下面代码所示:

     1 package lkl;
     2 
     3 import java.util.Arrays;
     4 
     5 ///spllit()是String类自带的一个正则表达式工具
     6 ///其功能是:将字符串重正则表达式匹配的地方切开成为一个个单词
     7 ///其实就是指定分隔符将字符串分成许多个单词(分隔符会消失),返回String数组
     8 public class RepalceTest {
     9 
    10     public static String knights="Then, when you have found the shrubbery, you must"
    11         +"cut dwon the mightiest tree forest..."+"with... a herring";
    12     }
    13 
    14     public static void main(String[] args){
    15         ///String类还只带了一个"替换"的正则表示式工具
    16         ///可以选择只替换第一个匹配的子串或替换所有匹配的地方
    17 
    18         //将第一个以f开头并且后面至少有一个字符的子串替换成"located"
    19         System.out.println(knights.replaceFirst("f\w+", "located"));
    20 
    21         ///将字符串中含有的前三个子串替换成后面的字符串
    22         System.out.println(knights.replaceAll("shrubbery|tree|herring","banana"));
    23     }/*Output
    24           Then, when you have located the shrubbery, you mustcut dwon the mightiest tree forest...with... a herring
    25          Then, when you have found the banana, you mustcut dwon the mightiest banana forest...with... a banana
    26 
    27     */
    28 }

    三.使用regex包创建正则表达式 
    上面通过String类使用正则的方式有一个很大的问题:我们写的正则表达式不能重复利用.实际上我们可以用Pattern类和Matcher类(这两个类都位于regex包下)构造更加强大的灵活的正则表达式.大概的步骤是:我们创建一个表示正则表达式的字符串,然后用static Pattern.compile()方法编译得到一个Pattern对象,然后将要我们要检索的字符串传入Pattern对象的matcher()方法,然后matcher()方法可以生成一个Matcher对象,这个Matcher对象有很多的功能可以调用.具体的过程就像下面这样:

     1 import java.util.regex.*;
     2 
     3 public class MatchTest {
     4 
     5     ///定义正则表示式数组,注意""要转义
     6     public static String[] pattern ={"^Java","\Breg.*","n.w\s+h(a|i)s"
     7     ,"s?","s*","s+","s{4}","s{1}.","s{0,3}"};
     8     //待匹配数组
     9    public static String str="Java now has regular expressions";
    10     public static void main(String[] args){
    11         for(String pa : pattern){
    12 
    13             //根据传入的String类型正则表达式,Pattern编译生成一个Pattern对象
    14             Pattern p= Pattern.compile(pa);
    15 
    16             //将p对象与一个字符串关联生成一个Matcher对象
    17             Matcher m =p.matcher(str);
    18             System.out.println("正则表达式:  ""+pa+""  在字符串上匹配: "+m.matches());
    19         }/*Output
    20     正则表达式:  "^Java"  在字符串上匹配: false
    21     正则表达式:  "Breg.*"  在字符串上匹配: false
    22     正则表达式:  "n.ws+h(a|i)s"  在字符串上匹配: false
    23     正则表达式:  "s?"  在字符串上匹配: false
    24     正则表达式: "s*"  在字符串上匹配: false
    25     正则表达式: "s+"  在字符串上匹配: false
    26     正则表达式: "s{4}"  在字符串上匹配: false
    27     正则表达式:"s{1}."  在字符串上匹配: false
    28     正则表达式:"s{0,3}" 在字符串上匹配: false
    29         */
    30     }
    31 }

    Matcher对象包括了很多的可以调用的方法,包括与上面String类相同的matches(),split(),repalceFirst(), 
    replaceFirst(),replaceAll()等方法,这些方法的用法和上面String类展示的是一样的.但是还有一些更加灵活的方法,如下面的代码所示.

     1 import java.util.regex.Matcher;
     2 import java.util.regex.Pattern;
     3 
     4 //Matcher的find()方法可以查找到多个匹配
     5 public class MatchFindTest {
     6 
     7       public static void main(String[] args){
     8           ///这个匹配的意思是:匹配字母
     9           Matcher m=Pattern.compile("\w+").matcher("Evening is full  of"
    10                 + "the linnet's wings");
    11           while(m.find())
    12               System.out.print(m.group()+" ");
    13           System.out.println();
    14           int i=0;
    15           //这个重载的版本可以向里面传入一个参数,指定匹配的起点
    16           while(m.find(i)){
    17               System.out.print(m.group()+" ");
    18               i++;
    19           }
    20           System.out.println();
    21       }/*Output
    22           Evening is full ofthe linnet s wings 
    23           Evening vening ening ning ing ng g is is s full full ull ll l ofthe ofthe ofthe fthe the he e linnet linnet innet nnet net et t s s wings wings ings ngs gs s 
    24       */
    25 }
     1 import java.util.regex.*;
     2 
     3 //lookingAt()判断该字符串的第一部分是否匹配
     4 //group()方法可以将上次匹配成功的部分记录下来
     5 //start()方法返回先前匹配的起始位置
     6 //end()方法返回先前匹配的最后字符的索引加1的值
     7 public class MatcherStartEnd {
     8 
     9     public static String str="This ais a example";
    10     public static void main(String[] args){
    11 
    12           Pattern p=Pattern.compile("\w+is");
    13           Matcher m=p.matcher(str);
    14           System.out.print("longkingAt():  ");
    15           if(m.lookingAt())
    16                  System.out.println(m.group()+" "+m.start()+" "+m.end());
    17 
    18          m=p.matcher(str);
    19          System.out.print("find():  ");
    20          while(m.find()){
    21              System.out.print(m.group()+" "+m.start()+"  "+m.end()+" ");
    22          }
    23         System.out.println("");
    24     }/*Output
    25          longkingAt():  This 0 4
    26            find():  This 0  4 ais 5  8 
    27 
    28     */
    29 }
     1 import java.util.regex.Matcher;
     2 import java.util.regex.Pattern;
     3 
     4 ///在调用Pattern的compile()函数时可以传入一些常量标记
     5 ///下面演示了两个最常用的常量表达式
     6 public class ReFlags {
     7 
     8     public static void main(String[] args){
     9         //Pattern.MULTILINE表示表达式^和$分别匹配一行的开始和介绍(默认匹配是整个字符串的开始和结束)
    10         //Pattern.CASE_INSENSITIVE表示匹配时忽略大小写
    11         Pattern p= Pattern.compile("^java",Pattern.MULTILINE|Pattern.CASE_INSENSITIVE);
    12         Matcher m=p.matcher("java has regex
    Java has regex
    "+
    13         "JAVA has pretty good regular expressions
    ");
    14         while(m.find()){
    15             System.out.println(m.group());
    16         }/*Output
    17             java
    18             Java
    19             JAVA
    20         */
    21     }
    22 }
     1 import java.util.regex.*;
     2 
     3 ///Matcher对象的reset()方法可以将现有的Matcher对象应用于一个新的字符序列
     4 ///如果使用不带参数的rest()(不传入一个字符串),则表示将Matcher对象
     5 //重新设置到当前字符序列的起始位置
     6 public class Reset {
     7     public static void main(String[] args){
     8         Matcher m=Pattern.compile("[frb][aiu][gx]").matcher("fix the rug with bags");
     9         while(m.find()){
    10             System.out.print(m.group()+" ");
    11         }
    12         System.out.println();
    13         m.reset("fix the rig with rags");
    14         while(m.find()){
    15             System.out.print(m.group()+" ");
    16         }
    17         System.out.println();
    18     }/*Output
    19         fix rug bag 
    20         fix rig rag 
    21     */
    22 }

    转载:http://blog.csdn.net/acm_lkl/article/details/46473007

  • 相关阅读:
    Spring、Spring Boot 和 Spring Cloud 的关系
    Spring Boot 如何设置支持跨域请求?
    什么是嵌入式服务器?我们为什么要使用嵌入式服务器呢?
    nginx配置域名,不要端口
    域名解析以及nginx服务器设置
    为什么使用nginx
    RabbitMQ下载与安装(window版)
    spring的@ComponentScan注解
    spring的@EnableScheduling注解
    日志切割: logrotate、python、shell实现
  • 原文地址:https://www.cnblogs.com/benchao/p/5263247.html
Copyright © 2011-2022 走看看