简体   繁体   English

在R中使用gregexpr按名称访问正则表达式组结果

[英]Access regex group results by name using gregexpr in R

How can I access all matches with groupings (ie label ) using gregexpr() in R? 如何在R中使用gregexpr()访问具有分组(即label )的所有匹配项?

s <- "aaa123bbb345ccc"
p <- "(?<label>\\d+)"
m <- gregexpr(p, s, perl = TRUE)

I am interested in printing the matches in m but referencing the group name <label1> . 我有兴趣在m中打印匹配项,但引用组名<label1> This can be easily done in C# but I'm struggling in R and I cannot figure out how to do this from the CRAN docs. 这可以在C#中轻松完成,但是我在R中苦苦挣扎,我无法从CRAN文档中弄清楚如何做到这一点。

Edit: C# code below requested by G Grothendieck : 编辑: G Grothendieck要求的以下C#代码:

string s = "aaa123bbb345ccc";
string p = @"(?<label>\d+)";
Regex r = new Regex(p);
Match m = r.Match(s);
if (m.Success)
{
    Console.WriteLine(m.Groups["label"].Value);
}

This will return only the substrings associated with label . 这将仅返回与label关联的子字符串。

st <- attr(m[[1]], "capture.start")[, "label"]
len <- attr(m[[1]], "capture.length")[, "label"]
substring(s, st, st + len - 1)
## [1] "123" "345"

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

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