代码改变世界

[Android Tips] 21. Regex Named Groups in Android

2016-07-12 20:53  shaobin0604  阅读(495)  评论(0编辑  收藏  举报

Android SDK 并没有包含 Java 7 新增加的命名捕获组功能,需要使用第三方库 https://github.com/tony19/named-regexp

import com.google.code.regexp.Pattern;
import com.google.code.regexp.Matcher;

public class NamedRegexpTest {
    public static void main(String[] args) {
        // pattern contains capture group, named "foo"
        Matcher m = Pattern.compile("(?<foo>\\w+) world").matcher("hello world!");
        m.find();
        System.out.println(m.group("foo")); // prints "hello"
    }
}

参考