Java Basics Part 16/20 - Regular Expressions

Java Basics Part 16/20 - Regular Expressions

目录


Java 为正则表达式的模式匹配提供了 java.util.regex 包。
正则表达式主要用来匹配或者查询符合某个模式的字符串。

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

  • Pattern Class: 正则表达式编译后 产生 Pattern 对象。 Pattern 类没有构造器,为了产生一个 Pattern,必须调用 Pattern 的 compile() 方法,它会返回一个 Pattern 对象。Pattern 类的静态方法的第一个参数都是一个 正则表达式。
  • Matcher Class: Matcher 对象是一个引擎,用来解释 pattern,并且在输入字符串上执行匹配操作。与 Pattern 类一样,Matcher 类也不提供构造器。可以 Pattern 对象的 matcher() 方法来获得一个 Matcher 对象。
  • PatternSyntaxException: 用来指示 正则表达式 有语法错误的异常类。

捕获组

捕获组把多个字符当成一个整体。把多个字符放在一个括号中,就创建了一个捕获组。例如,正则表达式 (dog) 就创建了一个组,这个组里含有字母 d,o 和 g。

可以从左到右对左半边括号计数来得到捕获组的数目。例如,表达式 ((A)(B(C))),有以下几个组:

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

为了得到表达式中的捕获组数目,可以调用 matcher 对象的 groupCount() 方法。这个方法返回了一个 matcher 的 pattern 中含有的捕获组的数目。

还有一个特殊的组,group 0,这个组总是代表整个表达式。groupCount 不会对这个组进行计数。

举例:
下面这个例子演示了怎样在字符串中找到一个数字。

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class RegexMatches
{
    public static void main( String args[] ){

      // String to be scanned to find the pattern.
      String line = "This order was placed for QT3000! OK?";
      String pattern = "(.*)(\\d+)(.*)";

      // Create a Pattern object
      Pattern r = Pattern.compile(pattern);

      // Now create matcher object.
      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) );
      } else {
         System.out.println("NO MATCH");
      }
   }
}

// output
Found value: This order was placed for QT3000! OK?
Found value: This order was placed for QT300
Found value: 0

可见,group 0 就是整个表达式。


正则表达式语法

下标列出了 Java 中所有可用的的正则表达式元字符。

Subexpression Matches
^ 一行的开头
$ 一行的结尾
. 任意字符除了换行符
[…] 匹配中括号中的任一个字符
[^…] 匹配任意一个不在中括号中的字符
\A 整个字符串的开头
\z 整个字符串的结尾
\Z 整个字符串的结尾,除了行终止符
re* 匹配 0 或 多个前面的表达式
re+ 匹配 1 或 多个前面的表达式
re? 匹配 0 或 1 个前面的表达式
re{n} 匹配正好 n 个前面的表达式
re{n,} 匹配至少 n 个前面的表达式
re{n,m} 匹配最少 n 最多 m 个前面的表达式
a|b 匹配 a 或 b
(re) 组表达式并记住匹配的文本
(?:re) 组表达式但是不记住匹配的文本
(?> re) 匹配单独的模式,不要反向追踪
\w 匹配单词字符
\W 匹配非单词字符
\s 匹配空白字符 [\t\b\r\f]
\S 匹配非空白字符
\d 匹配数字
\D 匹配非数字
\G 最后一次匹配结束的匹配点
\n 反向引用第 n 个捕获组
\b 在中括号外是 匹配单词边界,中括号内是匹配 backspace
\B 匹配非单词边界
\n, \t, etc 匹配 换行,tab 等
\Q 所有的字符都是普通字符,包括转义字符,直到遇到\E
\E 与 \Q 对应

Matcher 类方法

Index 方法

Index 方法可以精确返回 匹配 出现在 输入中 的位置

SN Methods with Description
1 public int start():返回前一个匹配的开始位置
2 public int start(int group):返回匹配的组的开始的位置
3 public int end():返回匹配的最后一个字符之后的偏移
4 public int end(int group):返回匹配的组的最后一个字符之后的偏移

Study 方法

Study 方法查看输入字符串,并且返回一个 boolean,说明 pattern 是否能匹配。

SN Methods with Description
1 public boolean lookingAt():尝试使用 pattern 从起始位置匹配输入序列
2 public boolean find():尝试使用 pattern 匹配输入序列
3 public boolean find(int start):尝试从 start 处使用 pattern 匹配输入序列
4 public boolean matches():尝试使用 pattern 匹配整个输入序列

Replacement 方法

Replacement 方法主要用来替换字符串中的文本

SN Methods with Description
1 public Matcher appendReplacement(StringBuffer sb, String replacement):把匹配的内容换成 replacement
2 public StringBuffer appendTail(StringBuffer sb):剩下的没有匹配的全都添加到 sb 中
3 public String replaceAll(String replacement)
4 public String replaceFirst(String replacement)
5 public static String quoteReplacement(String s)

栗子

start() 和 end()

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); // get a matcher object
       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());
      }
   }
}

// output
atch number 1
start(): 0
end(): 3
atch number 2
start(): 4
end(): 7
atch number 3
start(): 8
end(): 11
atch number 4
start(): 19
end(): 22

matches() 和 lookingAt()

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 Pattern pattern;
    private static Matcher matcher;

    public static void main( String args[] ){
       pattern = Pattern.compile(REGEX);
       matcher = pattern.matcher(INPUT);

       System.out.println("Current REGEX is: "+REGEX);
       System.out.println("Current INPUT is: "+INPUT);

       System.out.println("lookingAt(): "+matcher.lookingAt());
       System.out.println("matches(): "+matcher.matches());
   }
}

// output
Current REGEX is: foo
Current INPUT is: fooooooooooooooooo
lookingAt(): true
matches(): false

replaceFirst() 和 replaceAll()

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);
   }
}

// output
The cat says meow. All cats say meow.

appendReplacement() 和 appendTail()

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class RegexMatches
{
   private static String REGEX = "a*b";
   private static String INPUT = "aabfooaabfooabfoob";
   private static String REPLACE = "-";
   public static void main(String[] args) {
      Pattern p = Pattern.compile(REGEX);
      // get a matcher object
      Matcher m = p.matcher(INPUT);
      StringBuffer sb = new StringBuffer();
      while(m.find()){
         m.appendReplacement(sb,REPLACE);
      }
      m.appendTail(sb);
      System.out.println(sb.toString());
   }
}

// output
-foo-foo-foo-

PatternSyntaxException 类的方法

PatternSyntaxException 用来表明正则表达式中的语法错误的。

SN Methods with Description
1 public String getDescription():返回错误描述
2 public int getIndex():返回错误号
3 public String getPattern():返回错误的正则表达式
4 public String getMessage():一堆错误信息,基本上是以上三者的汇总吧
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章