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("(?<foo>\\w+) world").matcher("hello world!");
        m.find();
        System.out.println(m.group("foo")); // prints "hello"
    }
}

java 1.8 :


image.png
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

友情链接更多精彩内容