微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

字符串:正则表达式的使用



/*
* 2018年3月30日15:53:17
* 代码目的:
* 演示正则表达式java.util.regex中两个类的使用。
* 1, 导入java.util.regex
* 2, 使用static Pattern.compile()方法来编译你的正则表达式,
它会根据你的String类型的正则表达式生成一个Pattern对象。
* 3, 把你想要检索的字符串传入Pattern对象的matcher()方法
* 4, matcher()方法生成一个Matcher对象,有很多功能可用,
* 它的replaceAll()方法能将所有匹配的部分都替换成你传入的参数。
*
* 该程序需要使用命令行参数
* */

//: strings/TestRegularExpression.java
// Allows you to easily try out regular expressions.
// {Args: abcabcabcdefabc "abc+" "(abc)+" "(abc){2,}" }
import java.util.regex.*;
import static net.mindview.util.Print.*;

public class TestRegularExpression {
  public static void main(String[] args) {
    if(args.length < 2) {
      print("Usage:\njava TestRegularExpression " +
        "characterSequence regularExpression+");
      System.exit(0);
    }
    print("Input: \"" + args[0] + "\"");
    for(String arg : args) {
      print("Regular expression: \"" + arg + "\"");
      Pattern p = Pattern.compile(arg);
      Matcher m = p.matcher(args[0]);
      /*
       * Regular expression: "abc+"
			Match "abc" at positions 0-2
			Match "abc" at positions 3-5
			Match "abc" at positions 6-8
			Match "abc" at positions 12-14
			通过该输出,可以看到在字符串匹配一个模式时,会从头开始进行,
			在第一次匹配时,匹配的位置是0--3,而匹配的内容由group()显示
			起始和结束位置由start和end方法显示。
			再次进入循环时,匹配从end方法所指向的位置开始进行。
       * */
      while(m.find()) {
        print("Match \"" + m.group() + "\" at positions " +
          m.start() + "-" + (m.end() - 1));
      }
    }
  }
} /* Output:
Input: "abcabcabcdefabc"
Regular expression: "abcabcabcdefabc"
Match "abcabcabcdefabc" at positions 0-14
Regular expression: "abc+"
Match "abc" at positions 0-2
Match "abc" at positions 3-5
Match "abc" at positions 6-8
Match "abc" at positions 12-14
Regular expression: "(abc)+"
Match "abcabcabc" at positions 0-8
Match "abc" at positions 12-14
Regular expression: "(abc){2,}"
Match "abcabcabc" at positions 0-8
*///:~

原文地址:https://www.jb51.cc/regex/357563.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐