第十三章 字符串(三)之正则表达式

一、正则表达式的“\”问题   

在Java的字符串中"\"有两个功能

  (一)代表特殊字符:\t代表制表符,\n代表换行....等。

  (二)代表转义: 在字符串中,如果出现 \ 及 " 等会造成代码歧义,所以要用\"进行转义

在Java的正则表达式中\也是表示两个功能

  (一)代表特殊功能的字符:如\d代表数字[0-9]

  (二)代表转义,和上面一样,当出现字符歧义时,加上\表示普通字符。

java正则表达式中需要转义的字符:

^ $ . [ ] * \ ? + { } | ( )

这些字符在正则表达式中都有特殊意义。

例如,要想用正则表达式匹配一个普通的'\'字符,则正则表达式为"\\\\"四个斜杠。因为'\'在正则表达式中需要转义,就成类"\\",正则表达式中的斜杠,在字符串中表示也需要转义,即"\\\\"。

                       

二、StringAPI中的正则表达式使用

public class Demo5 {

    public static void main(String[] args) {
        String s = new String("Living without an aim is like sailing without a compass.");
        System.out.println("Regex Expression \"\\\\s*without\\\\s+\":");
        for(String sub : s.split("\\s*without\\s+")) {
            System.out.println(sub);
        }
        //split()有个参数limit,限制切割次数,仅切割limit-1次,就是切成limit块
        System.out.println("Regex Expression \" \":");
        for(String sub : s.split(" ", 5)) {
            System.out.println(sub);
        }
        //把所有开头字母a的换成B
        System.out.println("Regex Expression \"\\\\s+a\"");
        System.out.println(s.replaceAll("\\s+a", " B"));
    }

}

 

输出结果:

 

结果说明:正则表达式,自己动手写起来真是不太容易写啊。

 

三、java.util.regex.*包中常使用的API

1、匹配操作相关API

import java.util.regex.*;

public class Demo6 {
    public static void  main(String[] args) {
        String s = "Arline ate eight apples and one orange while Anita hadn't any";
        Pattern p1 = Pattern.compile("^A.*y$");
        Matcher m1 = p1.matcher(s);
        System.out.println("matches(): " + m1.matches());
        
        Pattern p2 = Pattern.compile("^A\\w*\\b");
        Matcher m2 = p2.matcher(s);
        System.out.println("lookAt(): " + m2.lookingAt() + " " + m2.group() + 
                '(' + m2.start() + ',' + (m2.end()-1) + ")");
        
        Pattern p3 = Pattern.compile("(?i)((^[aeiou])|(\\b[aeiou]))\\w+[aeiou]\\b");
        Matcher m3 = p3.matcher(s);
        System.out.println("find(): ");
        while(m3.find()) {
            System.out.println(m3.group() + " " + m3.group(1) + " " + "(" +
                    m3.start() + "," + m3.end() + ")");
        }
    }
}
View Code

 

输出结果:

matches(): true
lookAt(): true Arline(0,5)
find():
Arline A (0,6)
ate a (7,10)
one o (28,31)
orange o (32,38)
Anita A (45,50)

结果说明:

matches(): 需要整个输入串与正则表达式匹配,才返回true。

lookingAt(): 必须从输入串头开始匹配,不必为整个串.

find(): 只要匹配到输入串的子串就ok。

find(in start): 重置匹配器,从指定索引开始扫描串进行匹配。

start(): 上一次匹配成功的子串起始索引。

end(): 上次匹配成功的子串的末尾字符索引加1。

group(): 返回上次匹配成功的子串。

group(int i): 返回前次匹配指定组号的字符串。

组号:A((B)C) 第0组为整个正则表达式,组1:(B)C,组2:B,被第几对括号括起来就是第几组。

 

2、替换操作相关API

import java.util.regex.*;

public class Demo7 {

    public static void main(String[] args) {
        String s = new String("Kelvin Li and Kelvin Chan are both "
                + "working in Kelvin Chen's KelvinSoftShop company");
        Pattern p = Pattern.compile("Kelvin");
        Matcher m = p.matcher(s);
        System.out.println("replaceFirst(): ");
        System.out.println(m.replaceFirst("Kevin"));
        System.out.println("replaceAll(): ");
        System.out.println(m.replaceAll("Kevin"));
        System.out.println("s: ");
        System.out.println(s);
        StringBuffer buffer = new StringBuffer();
        
        //一定要注意匹配器的状态
        Matcher m1 = p.matcher(s);
        
        while(m1.find()) {
            m1.appendReplacement(buffer, m1.group().toUpperCase());
        }
        m.appendTail(buffer);
        System.out.println(buffer);
        System.out.println(s);
    }

}
View Code

 

输出结果:

replaceFirst():
Kevin Li and Kelvin Chan are both working in Kelvin Chen's KelvinSoftShop company
replaceAll():
Kevin Li and Kevin Chan are both working in Kevin Chen's KevinSoftShop company
s:
Kelvin Li and Kelvin Chan are both working in Kelvin Chen's KelvinSoftShop company
KELVIN Li and KELVIN Chan are both working in KELVIN Chen's KELVINSoftShop company
Kelvin Li and Kelvin Chan are both working in Kelvin Chen's KelvinSoftShop company

 

结果说明:

String replaceFirst(String replacement): 替换第一个匹配成功的子串。

String replaceAll(String replacement): 替换所有匹配成功的子串。

appendReplacement(StringBuffer sb, String replacement): 将当前匹配子串替换为指定字符串,并且将替换后的子串以及其之前到上次匹配子串之后的字符串段添加到一个StringBuffer对象里。

appendTail(StringBuffer sb) 方法则将最后一次匹配工作后剩余的字符串添加到一个StringBuffer对象里。 

从此例中还可以看到无论如何去替换,原字符串是不改变的。

 

3、Pattern标记

介绍两个常用的Pattern标记吧。

Pattern.MULTILINE(?m): 多行模式,在此模式下^和$分别匹配一行的开始和结束,也可匹配整个串的开始和结束。但默认情况下,匹配整个串的开始结束。

Pattern.Case_INSENSITIVE(?i): 开启大小写不敏感模式。

import java.util.regex.*;
public class Demo8 {

    public static void main(String[] args) {
        String s = "JAVA\njava\nJava";
        Pattern p = Pattern.compile("(?m)(?i)java");
        Matcher m = p.matcher(s);
        while(m.find()) {
            System.out.println(m.group());
        }
    }

}

 

输出结果:

JAVA
java
Java

posted @ 2019-09-06 19:18  卑微芒果  Views(239)  Comments(0Edit  收藏  举报