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"]
^
It is the
MatchNamedGroupCollectionthat allows getting by name, theMatchGroupCollectiononly 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"]