Android 正则匹配 regex named groups

android java regex named groups: https://stackoverflow.com/questions/27834463/android-java-regex-named-groups

named groups

http://userguide.icu-project.org/strings/regexp

由于业务需求,需要用到正则。确定下来要用到 'named group'。我的记忆中,Java是没有这个东西的,当然自己一直也没有深入研究过正则这一块。

后来经过研究发现,其实Java 7 就开始支持了的。 就兴高采烈的让同事在Android gradle build 配置文件中设置用1.7编译,然并卵,依然没有找到 'match.group("named")' 这样的API。

在后来看到 android java regex named groups 才确定,Android确实不支持。具体可以看到下面的回复内容:

Android Pattern class implementation is provided by ICU, to be precise, ICU4C.
The regular expression implementation used in Android is provided by ICU. The notation for the regular expressions is mostly a superset of those used in other Java language implementations. This means that existing applications will normally work as expected, but in rare cases Android may accept a regular expression that is not accepted by other implementations.
And ICU4C currently doesn't support named capturing group. You have to fall back on numbered capturing groups.
ICU does not support named capture groups. http://bugs.icu-project.org/trac/ticket/5312
You need to write a wrapper and parse the expression yourself to provide named capturing group capability, if you really need the feature.

解决方案

Stack Overflow 回复下面就有:使用这个库: 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("(?\\w+) world").matcher("hello world!");
        m.find();
        System.out.println(m.group("foo")); // prints "hello"
    }
}

java 1.8 :


Android 正则匹配 regex named groups_第1张图片
image.png

你可能感兴趣的:(Android 正则匹配 regex named groups)