redrom
redrom

Reputation: 11642

Regex pattern in Android studio throws error : This named group syntax is not supported

i have the following regex pattern which is in the Android Studio throwing error This named group syntax is not supported.

Pattern pattern = Pattern.compile("(?<new>network=\\{|(?!^)\\G)\\s*(?<key>\\w+)=\"?(?<value>[^\"\n]+)\"?");

But in the Ideone example is it working:

http://ideone.com/rMLk3K

I tried to solve it using the Regular Expression testing for Java

http://www.regexplanet.com/advanced/java/index.html

And there i got the following error:

Illegal repetition near index 17 "(?<new>network=\\{|(?!^)\\G)\\s*(?<key>\\w+)=\"?(?<value>[^\"\n]+)\"?" 

What can be wrong please?

Many thanks for any advice.

Upvotes: 3

Views: 4108

Answers (2)

Eric Schlenz
Eric Schlenz

Reputation: 2581

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.

Upvotes: 4

nhahtdh
nhahtdh

Reputation: 56809

Android implements the Pattern class by writing a wrapper around ICU4C. Named capturing group is not supported by ICU4C prior to ICU 55.

At the time of answering (Sep 25th 2015), Android code base was stuck at ICU 49.1.1 on the latest tag at the time of writing (android-5.1.1_r18), so the regex doesn't compile. Since then, Android has updated to ICU 55.1 in marshmallow-release branch, so the regex should compile from this version of Android. However, even if the regex compiles, without changes to the API on Java side, you won't be able to address the capturing groups by name.

For now, just write the regex without named groups and extract the matched content by group number as per normal:

Pattern.compile("(network=\\{|(?!^)\\G)\\s*(\\w+)=\"?([^\"\n]+)\"?");

You can access the groups new, key, value at groups numbered 1, 2, 3 respectively.

Upvotes: 8

Related Questions