简体   繁体   English

如何按名称访问捕获组?

[英]How to access a capture group by name?

Say I have a MatchResult m :假设我有一个MatchResult m

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

How can I access the group named "foo" by name?如何按名称访问名为“foo”的组? According to the docs MatchGroupCollection implements the get(String) operator , but if I try it I get an exception:根据文档MatchGroupCollection实现了get(String)运算符,但如果我尝试它,我会得到一个异常:

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

It is the MatchNamedGroupCollection that allows getting by name, the MatchGroupCollection only allows getting by integer index.MatchNamedGroupCollection允许按名称获取, MatchGroupCollection只允许按 integer 索引获取。

So you need to check the group type before getting the match by name.因此,您需要在按名称获取匹配项之前检查组类型。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM