Date
May. 20th, 2024
 
2024年 4月 13日

Post: Java 与 RegEx 浅析 002: 小试 java.util.regex

Java 与 RegEx 浅析 002: 小试 java.util.regex

Published 12:09 Sep 19, 2013.

Created by @ezra. Categorized in #Programming, and tagged as #Java.

Source format: Markdown

Table of Content

正则表达式包 java.util.regex 的使用十分简单,它的功能由下列内容组成:

  • java.util.regex.Pattern

    • Pattern 对象就是编译好的正则表达式,它可以应用于任意多的字符串
  • java.util.regex.Matcher

    • Matcher 对象对应单独的实例,它表示将正则表达式应用到某个具体的目标字符串上
  • 接口 java.util.regex.MatchResult

    • MatchResult 是 Java 5.0 之后的新特性,它包含了成功匹配到的数据,这些数据可以在下一次匹配前从 Matcher 本身获取,也可以提出作为 MatchResult 保存
  • 异常 java.util.regex.PatternSyntaxException

    • 当你使用的正则表达式格式不正确时,会产生 PatternSyntaxException 异常,它继承自 java.lang.IllegalArgumentException,是一个 Unchecked Exception

大多数时候你可能只会用到前面的两个类,我们来看一个完整的匹配示例:

improt java.util.regex.*;
public class Simple {
    public static void main(String[] args) {
        String sourceText = "My 1st test String";
        String regexText = "\\d+\\w+";
        Pattern p = Pattern.complie(regexText);
        Matcher m = p.matcher(sourceText);

        if (m.find) {
            String matchedText = m.group();
            int matchedFrom = m.start();
            int matchedTo = m.end();
            System.out.println("matched [" + matchedText + "]" + "from" + matchedFrom + "to" + marchedTo);
        } else {
            System.out.println("Didn't match");
        }
    }
}

输出结果是:

matched [1st] from 3 to 6
Pinned Message
HOTODOGO
I'm looking for a SOFTWARE PROJECT DIRECTOR / SOFTWARE R&D DIRECTOR position in a fresh and dynamic company. I would like to gain the right experience and extend my skills while working in great teams and big projects.
Feel free to contact me.
For more information, please view online résumé or download PDF
本人正在寻求任职 软件项目经理 / 软件技术经理 岗位的机会, 希望加⼊某个新鲜⽽充满活⼒的公司。
如有意向请随时 与我联系
更多信息请 查阅在线简历下载 PDF