字符串:正则表达式组和模式标记的使用

前端之家收集整理的这篇文章主要介绍了字符串:正则表达式组和模式标记的使用前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。


/*
* 2018年3月30日16:17:27
* 代码目的:
* 演示正则表达式中组的概念和模式标记的使用。
* 组是用括号划分的正则表达式,可以根据组的编号来引用某个组。
* 组号为0表示整个表达式
* A(B(C))D,其中有三个组,组0ABCD, 组1,BC,组2C
* "(?m)(\\S+)\\s+((\\S+)\\s+(\\S+))$"作为正则表达式
* (?m)不是组而是模式标记
* 组0是整体
* 组1是\\S+
* 组2是\\S+\\s+\\S+
* 组3\\S+
* 组4是\\S+
* 目的是捕获每行的后三个词,每行最后以$结束。
因为是多行模式,所以必须在序列开头添加(?m)模式标记,否则$与
整个序列的末端相匹配。
模式标记也可以在compile中指定:
public static Pattern compile(String regex,
int flags)将给定的正则表达式编译到具有给定标志的模式中。
常用的模式标记如下:
Pattern.CASE_INSENSITIVE(?i)
Pattern.DOTALL(?s)
Pattern.MULTILINE(?m)

* */

//: strings/Groups.java
import java.util.regex.*;
import static net.mindview.util.Print.*;

public class Groups {
  static public final String POEM =
    "Twas brillig,and the slithy toves\n" +
    "Did gyre and gimble in the wabe.\n" +
    "All mimsy were the borogoves,\n" +
    "And the mome raths outgrabe.\n\n" +
    "Beware the Jabberwock,my son,\n" +
    "The jaws that bite,the claws that catch.\n" +
    "Beware the Jubjub bird,and shun\n" +
    "The frumIoUs Bandersnatch.";
  static {
	  System.out.println(POEM);
  }
  public static void main(String[] args) {
    Matcher m =
      Pattern.compile("(?m)(\\S+)\\s+((\\S+)\\s+(\\S+))$")
        .matcher(POEM);
    //由输出可以看到,诗歌有多行组成,程序的意图是要与每行进行匹配
    //因此在正则表达式中添加了模式标记(?m),显示的告知正则
    //表达式注意输入序列中的换行符。
    System.out.println("---------------");
    while(m.find()) { 
    	//m.groupCount()返回的值为4.组0 不算在内。
      for(int j = 0; j <= m.groupCount(); j++)
        printnb("[" + m.group(j) + "]");
      print();
    }
  }
} /* Output:
Twas brillig,and the slithy toves
Did gyre and gimble in the wabe.
All mimsy were the borogoves,And the mome raths outgrabe.

Beware the Jabberwock,The jaws that bite,the claws that catch.
Beware the Jubjub bird,and shun
The frumIoUs Bandersnatch.
---------------
[the slithy toves][the][slithy toves][slithy][toves]
[in the wabe.][in][the wabe.][the][wabe.]
[were the borogoves,][were][the borogoves,][the][borogoves,]
[mome raths outgrabe.][mome][raths outgrabe.][raths][outgrabe.]
[Jabberwock,][Jabberwock,][my son,][my][son,]
[claws that catch.][claws][that catch.][that][catch.]
[bird,and shun][bird,][and shun][and][shun]
[The frumIoUs Bandersnatch.][The][frumIoUs Bandersnatch.][frumIoUs][Bandersnatch.]
*///:~

猜你在找的正则表达式相关文章