提取 R 中所有括号内的信息 [英] Extract info inside all parenthesis in R

查看:42
本文介绍了提取 R 中所有括号内的信息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字符串以及如何提取多个括号内的信息.目前我可以使用下面的代码从最后一个括号中提取信息.我该怎么做才能提取多个括号并作为向量返回?

I have a character string and what to extract the information inside of multiple parentheses. Currently I can extract the information from the last parenthesis with the code below. How would I do it so it extracts multiple parentheses and returns as a vector?

j <- "What kind of cheese isn't your cheese? (wonder) Nacho cheese! (groan) (Laugh)"                                                          
sub("\\).*", "", sub(".*\\(", "", j)) 

当前输出为:

[1] "Laugh"

所需的输出是:

[1] "wonder" "groan"  "Laugh" 

推荐答案

这是一个例子:

> gsub("[\\(\\)]", "", regmatches(j, gregexpr("\\(.*?\\)", j))[[1]])
[1] "wonder" "groan"  "Laugh" 

我认为这应该很有效:

> regmatches(j, gregexpr("(?=\\().*?(?<=\\))", j, perl=T))[[1]]
[1] "(wonder)" "(groan)"  "(Laugh)" 

但结果包括括号...为什么?

but the results includes parenthesis... why?

这有效:

regmatches(j, gregexpr("(?<=\\().*?(?=\\))", j, perl=T))[[1]]

感谢@MartinMorgan 的评论.

Thanks @MartinMorgan for the comment.

这篇关于提取 R 中所有括号内的信息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆