18.正则表达式

1.概述

正则表达式定义了字符串的模式。

正则表达式可以用来搜索、编辑或处理文本。

正则表达式并不仅限于某一种语言,但是在每种语言中有细微的差别。

正则表达式实例

一个字符串其实就是一个简单的正则表达式,例如 Hello World 正则表达式匹配 "Hello World" 字符串。

.(点号)也是一个正则表达式,它匹配任何一个字符如:"a" 或 "1"。

下表列出了一些正则表达式的实例及描述:


Java入门 - 语言基础 - 18.正则表达式

正则表达式实例

Java 正则表达式和 Perl 的是最为相似的。

java.util.regex 包主要包括以下三个类:

  • Pattern 类:pattern 对象是一个正则表达式的编译表示。Pattern 类没有公共构造方法。要创建一个 Pattern 对象,你必须首先调用其公共静态编译方法,它返回一个 Pattern 对象。该方法接受一个正则表达式作为它的第一个参数。
  • Matcher 类:Matcher 对象是对输入字符串进行解释和匹配操作的引擎。与 Pattern 类一样,Matcher 也没有公共构造方法。你需要调用 Pattern 对象的 matcher 方法来获得一个 Matcher 对象。
  • PatternSyntaxException 类:PatternSyntaxException 是一个非强制异常类,它表示一个正则表达式模式中的语法错误。

以下实例中使用了正则表达式 <strong>.*work100.* 用于查找字符串中是否包了 <strong>work100 子串:

<code>import java.util.regex.*; class RegexExample1{   public static void main(String[] args){      String content = "I am xiaojun " +        "from work100.net.";       String pattern = ".*work100.*";       boolean isMatch = Pattern.matches(pattern, content);      System.out.println("字符串中是否包含了 'work100' 子字符串? " + isMatch);   }}/<code>

实例输出结果为:

<code>字符串中是否包含了 'work100' 子字符串? true/<code>

2.捕获组

捕获组是把多个字符当一个单独单元进行处理的方法,它通过对括号内的字符分组来创建。

例如,正则表达式 (dog) 创建了单一分组,组里包含"d","o",和"g"。

捕获组是通过从左至右计算其开括号来编号。例如,在表达式((A)(B(C))),有四个这样的组:

  • ((A)(B(C)))
  • (A)
  • (B(C))
  • (C)

可以通过调用 matcher 对象的 groupCount 方法来查看表达式有多少个分组。groupCount 方法返回一个 int 值,表示 matcher 对象当前有多个捕获组。

还有一个特殊的组(group(0)),它总是代表整个表达式。该组不包括在 groupCount 的返回值中。

实例

下面的例子说明如何从一个给定的字符串中找到数字串:

<code>import java.util.regex.Matcher;import java.util.regex.Pattern; public class RegexMatches{    public static void main( String[] args ){       // 按指定模式在字符串查找      String line = "This order was placed for QT3000! OK?";      String pattern = "(\\\\D*)(\\\\d+)(.*)";       // 创建 Pattern 对象      Pattern r = Pattern.compile(pattern);       // 现在创建 matcher 对象      Matcher m = r.matcher(line);      if (m.find( )) {         System.out.println("Found value: " + m.group(0) );         System.out.println("Found value: " + m.group(1) );         System.out.println("Found value: " + m.group(2) );         System.out.println("Found value: " + m.group(3) );       } else {         System.out.println("NO MATCH");      }   }}/<code>

以上实例编译运行结果如下:

<code>Found value: This order was placed for QT3000! OK?Found value: This order was placed for QTFound value: 3000Found value: ! OK?/<code>

3.正则表达式语法

在其他语言中,\\\\ 表示:我想要在正则表达式中插入一个普通的(字面上的)反斜杠,请不要给它任何特殊的意义。

在 Java 中,\\\\ 表示:我要插入一个正则表达式的反斜线,所以其后的字符具有特殊的意义。

所以,在其他的语言中(如Perl),一个反斜杠 \\ 就足以具有转义的作用,而在 Java 中正则表达式中则需要有两个反斜杠才能被解析为其他语言中的转义作用。也可以简单的理解在 Java 的正则表达式中,两个 \\\\ 代表其他语言中的一个 \\,这也就是为什么表示一位数字的正则表达式是 \\\\d,而表示一个普通的反斜杠是 \\\\\\\\。


Java入门 - 语言基础 - 18.正则表达式

语法-1


Java入门 - 语言基础 - 18.正则表达式

语法-2


Java入门 - 语言基础 - 18.正则表达式

语法-3


Java入门 - 语言基础 - 18.正则表达式

语法-4


根据 Java Language Specification 的要求,Java 源代码的字符串中的反斜线被解释为 Unicode 转义或其他字符转义。因此必须在字符串字面值中使用两个反斜线,表示正则表达式受到保护,不被 Java 字节码编译器解释。例如,当解释为正则表达式时,字符串字面值 "\\b" 与单个退格字符匹配,而 "\\\\b" 与单词边界匹配。字符串字面值 "\\(hello\\)" 是非法的,将导致编译时错误;要与字符串 (hello) 匹配,必须使用字符串字面值 "\\\\(hello\\\\)"。

4.Matcher类的方法

索引方法

索引方法提供了有用的索引值,精确表明输入字符串中在哪能找到匹配:


Java入门 - 语言基础 - 18.正则表达式

索引方法

研究方法

研究方法用来检查输入字符串并返回一个布尔值,表示是否找到该模式:


Java入门 - 语言基础 - 18.正则表达式

研究方法


替换方法

替换方法是替换输入字符串里文本的方法:


Java入门 - 语言基础 - 18.正则表达式

替换方法


start和end方法

下面是一个对单词 "cat" 出现在输入字符串中出现次数进行计数的例子:

<code>import java.util.regex.Matcher;import java.util.regex.Pattern; public class RegexMatches{    private static final String REGEX = "\\\\bcat\\\\b";    private static final String INPUT =                                    "cat cat cat cattie cat";     public static void main(String[] args){       Pattern p = Pattern.compile(REGEX);       Matcher m = p.matcher(INPUT); // 获取 matcher 对象       int count = 0;        while(m.find()) {         count++;         System.out.println("Match number "+count);         System.out.println("start(): "+m.start());         System.out.println("end(): "+m.end());      }   }}/<code>

以上实例编译运行结果如下:

<code>Match number 1start(): 0end(): 3Match number 2start(): 4end(): 7Match number 3start(): 8end(): 11Match number 4start(): 19end(): 22/<code>

可以看到这个例子是使用单词边界,以确保字母 "c" "a" "t" 并非仅是一个较长的词的子串。它也提供了一些关于输入字符串中匹配发生位置的有用信息。

Start 方法返回在以前的匹配操作期间,由给定组所捕获的子序列的初始索引,end 方法最后一个匹配字符的索引加 1。

matches和lookingAt方法

matches 和 lookingAt 方法都用来尝试匹配一个输入序列模式。它们的不同是 matches 要求整个序列都匹配,而 lookingAt 不要求。

lookingAt 方法虽然不需要整句都匹配,但是需要从第一个字符开始匹配。

这两个方法经常在输入字符串的开始使用。

我们通过下面这个例子,来解释这个功能:

<code>import java.util.regex.Matcher;import java.util.regex.Pattern; public class RegexMatches{    private static final String REGEX = "foo";    private static final String INPUT = "fooooooooooooooooo";    private static final String INPUT2 = "ooooofoooooooooooo";    private static Pattern pattern;    private static Matcher matcher;    private static Matcher matcher2;     public static void main( String[] args ){       pattern = Pattern.compile(REGEX);       matcher = pattern.matcher(INPUT);       matcher2 = pattern.matcher(INPUT2);        System.out.println("Current REGEX is: "+REGEX);       System.out.println("Current INPUT is: "+INPUT);       System.out.println("Current INPUT2 is: "+INPUT2);        System.out.println("lookingAt(): "+matcher.lookingAt());       System.out.println("matches(): "+matcher.matches());       System.out.println("lookingAt(): "+matcher2.lookingAt());   }}/<code>

以上实例编译运行结果如下:

<code>Current REGEX is: fooCurrent INPUT is: foooooooooooooooooCurrent INPUT2 is: ooooofoooooooooooolookingAt(): truematches(): falselookingAt(): false/<code>

replaceFirst和replaceAll方法

replaceFirst 和 replaceAll 方法用来替换匹配正则表达式的文本。不同的是,replaceFirst 替换首次匹配,replaceAll 替换所有匹配。

下面的例子来解释这个功能:

<code>import java.util.regex.Matcher;import java.util.regex.Pattern; public class RegexMatches{    private static String REGEX = "dog";    private static String INPUT = "The dog says meow. " +                                    "All dogs say meow.";    private static String REPLACE = "cat";     public static void main(String[] args) {       Pattern p = Pattern.compile(REGEX);       // get a matcher object       Matcher m = p.matcher(INPUT);        INPUT = m.replaceAll(REPLACE);       System.out.println(INPUT);   }}/<code>

以上实例编译运行结果如下:

<code>The cat says meow. All cats say meow./<code>

appendReplacement和appendTail方法

Matcher 类也提供了 appendReplacement 和 appendTail 方法用于文本替换:

看下面的例子来解释这个功能:

<code>import java.util.regex.Matcher;import java.util.regex.Pattern; public class RegexMatches{   private static String REGEX = "a*b";   private static String INPUT = "aabfooaabfooabfoobkkk";   private static String REPLACE = "-";   public static void main(String[] args) {      Pattern p = Pattern.compile(REGEX);      // 获取 matcher 对象      Matcher m = p.matcher(INPUT);      StringBuffer sb = new StringBuffer();      while(m.find()){         m.appendReplacement(sb,REPLACE);      }      m.appendTail(sb);      System.out.println(sb.toString());   }/<code>

以上实例编译运行结果如下:

<code>-foo-foo-foo-kkk/<code>

PatternSyntaxException类的方法

PatternSyntaxException 是一个非强制异常类,它指示一个正则表达式模式中的语法错误。

PatternSyntaxException 类提供了下面的方法来帮助我们查看发生了什么错误。


Java入门 - 语言基础 - 18.正则表达式

PatternSyntaxException类提供的方法


分享到:


相關文章: