Java正则表达式分组获取字符串

Java正则表达式分组获取字符串

这是一段实用的利用Java正则表达式匹配与获取字符串的小函数,参考了网上的Java正则表达式的创立与搜索方法,这里我增加的代码实现的功能是分组匹配并最终获得想要的字符串。

代码实现

代码块

代码块语法遵循标准markdown代码,例如:

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

public class RegExpTest {
    public static void main(String[] args) {
        String text = "这是一个对象,其中的字段为name:Tom &(*^&(*^()&;age:20;others: Much things to learn.";
        String regExp = "(age):(\\d{1,2})";
        String age = regExpFind(text, regExp);
        if (age != null) {
            System.out.println("Succeeded!  we find " + age);
        }

    }

    public static String regExpFind(String text, String regExp) {
        String matchedRes = null;

        try {
            Pattern pattern = Pattern.compile(regExp);
            Matcher matcher = pattern.matcher(text);
            if (matcher.find()) {
                matchedRes = matcher.group(2);
                String matchedString = matcher.group();
                System.out.println("regExp匹配到的对应表达式: " + matchedString);
                System.out.println("匹配到的分组字符串 ; group(2)表示RegExp中第2个括号内的内容,结果为:" + matchedRes);

            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return matchedRes;

    }

}

>>console 输出结果
>regExp匹配到的对应表达式: age:20
匹配到的分组字符串 ; group(2)表示RegExp中第2个括号内的内容,结果为:20
Succeeded!  we find 20

猜你喜欢

转载自blog.csdn.net/innersense/article/details/44515085
今日推荐