Regex R正则表达式:在引号之间隔离字符串
我有一个字符串Regex R正则表达式:在引号之间隔离字符串,regex,r,quotes,Regex,R,Quotes,我有一个字符串myFunction(arg1=\'hop\,arg2=TRUE)。我想分离引号之间的内容(“hop\”,在本例中) 到目前为止,我一直在尝试,但没有成功: gsub(pattern="(myFunction)(\\({1}))(.*)(\\\"{1}.*\\\"{1})(.*)(\\){1})",replacement="//4",x="myFunction(arg1=\"hop\",arg2=TRUE)") 欢迎正则表达式大师的任何帮助 试试看 sub('[^\"]+\"(
myFunction(arg1=\'hop\,arg2=TRUE)
。我想分离引号之间的内容(“hop\”
,在本例中)
到目前为止,我一直在尝试,但没有成功:
gsub(pattern="(myFunction)(\\({1}))(.*)(\\\"{1}.*\\\"{1})(.*)(\\){1})",replacement="//4",x="myFunction(arg1=\"hop\",arg2=TRUE)")
欢迎正则表达式大师的任何帮助 试试看
sub('[^\"]+\"([^\"]+).*', '\\1', x)
#[1] "hop"
或
不需要\“
,因为”
也可以工作
sub('[^"]*("[^"]*.).*', '\\1', x)
#[1] "\"hop\""
如果有多个匹配项,正如@AvinashRaj在他的帖子中提到的,sub
可能没有那么大用处。使用stringi
的选项如下
library(stringi)
stri_extract_all_regex(x1, '"[^"]*"')[[1]]
#[1] "\"hop\"" "\"hop2\""
数据
xx您可以尝试:
str='myFunction(arg1=\"hop\",arg2=TRUE)'
gsub('.*(\\".*\\").*','\\1',str)
#[1] "\"hop\""
您还可以使用regmatches
函数。Sub或gsub仅适用于特定输入,对于一般情况,您必须抓取而不是删除
> x <- "myFunction(arg1=\"hop\",arg2=TRUE)"
> regmatches(x, gregexpr('"[^"]*"', x))[[1]]
[1] "\"hop\""
>x regmatches(x,gregexpr(“[^”]*”,x))[[1]]
[1] “\“跳”
要仅获取引号内的文本,请将上述函数的结果传递给gsub函数,该函数有助于删除引号
> 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"
>x gsub(“”,“”,regmatches(x,gregexpr(“([^”]*)”,x))[[1]]
[1] “跳”
>x gsub(“”,“”,regmatches(x,gregexpr(“([^“]*)”,x))[[1]]
[1] “跃点”“真”
当描述在引号之间时,您是否需要\“hop\”
或hop
作为答案?隔离是什么意思?您的预期输出是什么?例如\“hop”\“
非常感谢,这非常有效。您能解释第一种解决方案的基本原理吗?@RockScience第一种解决方案匹配所有非\“
的字符,即[^\”]+
,后跟一个\”
,然后使用捕获组(括号内)获取非\“
的字符,使用\\1
提取捕获组。使用paste0(\”,unlist(strsplit(x,“\”,perl=T))[2],“\”)
获取所需结果…(检查OP问题后的注释)
str='myFunction(arg1=\"hop\",arg2=TRUE)'
gsub('.*(\\".*\\").*','\\1',str)
#[1] "\"hop\""
> x <- "myFunction(arg1=\"hop\",arg2=TRUE)"
> regmatches(x, gregexpr('"[^"]*"', x))[[1]]
[1] "\"hop\""
> 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"