R正则表达式:在引号之间隔离一个字符串 [英] R regular expression: isolate a string between quotes

查看:35
本文介绍了R正则表达式:在引号之间隔离一个字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字符串 myFunction(arg1=\"hop\",arg2=TRUE).我想隔离引号之间的内容(在此示例中为 \"hop\")

I have a string myFunction(arg1=\"hop\",arg2=TRUE). I want to isolate what is in between quotes (\"hop\" in this example)

到目前为止我已经尝试过但没有成功:

I have tried so far with no success:

gsub(pattern="(myFunction)(\\({1}))(.*)(\\\"{1}.*\\\"{1})(.*)(\\){1})",replacement="//4",x="myFunction(arg1=\"hop\",arg2=TRUE)")

欢迎正则表达式大师的任何帮助!

Any help by a regex guru would be welcome!

推荐答案

您也可以使用 regmatches 功能.Sub 或 gsub 仅适用于特定输入,对于一般情况,您必须进行抓取而不是删除.

You could use regmatches function also. Sub or gsub only works for a particular input , for general case you must do grabing instead of removing.

> x <- "myFunction(arg1=\"hop\",arg2=TRUE)"
> regmatches(x, gregexpr('"[^"]*"', x))[[1]]
[1] "\"hop\""

要仅获取引号内的文本,然后将上述函数的结果传递给有助于删除引号的 gsub 函数.

To get only the text inside quotes then pass the result of above function to a gsub function which helps to remove the quotes.

> x <- "myFunction(arg1=\"hop\",arg2=TRUE)"
> gsub('"', '', regmatches(x, gregexpr('"([^"]*)"', x))[[1]])
[1] "hop"
> x <- "myFunction(arg1=\"hop\",arg2=\"TRUE\")"
> gsub('"', '', regmatches(x, gregexpr('"([^"]*)"', x))[[1]])
[1] "hop"  "TRUE"

这篇关于R正则表达式:在引号之间隔离一个字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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