Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java support for "(?<name>pattern)" in patterns [duplicate]

I was wondering if Java had an equivalent to C#’s named pattern matching. For example, in C# I can do something like this:

var pattern = @";(?<foo>\d{6});(?<bar>\d{6});";
var regex = new Regex(pattern , RegexOptions.None);
var match = regex.Match(";123456;123456;");

var foo = match.Groups["foo"].Success ? match.Groups["foo"].Value : null;
var bar = match.Groups["bar"].Success ? match.Groups["bar"].Value : null;

This just seems like a clean way to grab groups. Can Java do something similar, or do I need to grab groups based on index position?

String foo = matcher.group(0);
like image 202
aelstonjones Avatar asked Jun 22 '12 17:06

aelstonjones


2 Answers

This is supported starting in Java 7. Your C# code can be translated to something like this:

String pattern = ";(?<foo>\\d{6});(?<bar>\\d{6});";
Pattern regex = Pattern.compile(pattern);
Matcher matcher = regex.matcher(";123456;123456;");
boolean success = matcher.find();

String foo = success ? matcher.group("foo") : null;
String bar = success ? matcher.group("bar") : null;

You have to create a Matcher object which doesn't actually perform the regex test until you call find().

(I used find() because it can find a match anywhere in the input string, like the Regex.Match() method. The .matches() method only returns true if the regex matches the entire input string.)

like image 85
matts Avatar answered Nov 02 '22 07:11

matts


Java v1.7 now supports Perl-standard named groups like (?<name>...) and \k<name> in patterns.

You cannot have duplicate group names in the same pattern, which can be annoying in very complex cases where you are building up larger patterns out of smaller pieces out of your control. It also lacks relative indexing.

However, it should be enough for such simple things as you appear to be writing.

like image 30
tchrist Avatar answered Nov 02 '22 05:11

tchrist