hello) world").find("hello world")!! How can I access the group named "foo" by name? According t" /> hello) world").find("hello world")!! How can I access the group named "foo" by name? According t" /> hello) world").find("hello world")!! How can I access the group named "foo" by name? According t"/>

How to access a capture group by name?

1.1k views Asked by At

Say I have a MatchResult m:

>>> var m = Regex("(?<foo>hello) world").find("hello world")!!

How can I access the group named "foo" by name? According to the docs MatchGroupCollection implements the get(String) operator, but if I try it I get an exception:

>>> m.groups["foo"]
error: type mismatch: inferred type is String but Int was expected
m.groups["foo"]
         ^
1

There are 1 answers

1
Michiel Leegwater On

It is the MatchNamedGroupCollection that allows getting by name, the MatchGroupCollection only allows getting by integer index.

So you need to check the group type before getting the match by name.

Something like: (m.groups as MatchNamedGroupCollection)["foo"]