Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

android java regex named groups

I would like to use

matcher.group("login");

In android 8+ on eclipse, but no Matcher.group(String) seems to exist. Have you got a (built in) solution ?

like image 460
hanoo Avatar asked Jan 08 '15 06:01

hanoo


2 Answers

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.

like image 187
nhahtdh Avatar answered Oct 22 '22 12:10

nhahtdh


I thought I should share a solution I found. There is a fantastic library available on Github written by Tony Trinh (tony19) that enables one to use named regex groups.

Taken from the project page:

"This lightweight library adds support for named capture groups in Java 5/6 (and on Android).

This is a fork of the named-regexp project from Google Code (currently inactive)."

https://github.com/tony19/named-regexp

I've just tested this on Android 4.1.1 and above, and so far it's working like a charm. I was pleasantly surprised to find that I could simply replace my imports for Matcher and Pattern with the classes from this library, and all of my existing regexes that still used numbered groups still worked.

I hop this helps.

like image 28
Eric Schlenz Avatar answered Oct 22 '22 13:10

Eric Schlenz