加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-14 06:36:40 所属栏目:百科 来源:网络整理
导读:?? /* * 2018年3月30日16:17:27 * 代码目的: * 演示正则表达式中组的概念和模式标记的使用。 * 组是用括号划分的正则表达式,可以根据组的编号来引用某个组。 * 组号为0表示整个表达式 * A(B(C))D,其中有三个组,组0ABCD, 组1,BC,组2C * "(?m)(S+
??

/*
* 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+
* 组3S+
* 组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 tovesn" +
    "Did gyre and gimble in the wabe.n" +
    "All mimsy were the borogoves,n" +
    "And the mome raths outgrabe.nn" +
    "Beware the Jabberwock,my son,n" +
    "The jaws that bite,the claws that catch.n" +
    "Beware the Jubjub bird,and shunn" +
    "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.]
*///:~

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读