3

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"]
         ^
Aran-Fey
  • 39,665
  • 11
  • 104
  • 149
  • this might help: https://stackoverflow.com/questions/37088679/kotlin-regex-named-groups-support –  Sep 22 '19 at 08:36
  • 1
    Ah, apparently `get(String)` is only implemented on JVM and JRE8. Given that, does anyone have a suggestion how to easily access a capture group by name without using the `get` operator? – Aran-Fey Sep 22 '19 at 11:29

1 Answers1

0

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"]

Michiel Leegwater
  • 1,172
  • 4
  • 11
  • 27
  • 1
    Hmm, that throws an exception: `java.lang.UnsupportedOperationException: Retrieving groups by name is not supported on this platform.` – Aran-Fey Sep 22 '19 at 11:07