R regex: isolate string between quotes

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

I have tried so far without success:

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

Any help from regex gurus is appreciated!

+4
source share
4 answers

You can also use the function regmatches. Sub or gsub only works for a specific input, for the general case you should do a capture instead of deleting.

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

To get only the text inside the quotation marks, pass the result of the specified function to the gsub function, which helps to remove the quotation marks.

> 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"
+7
source

Try

 sub('[^\"]+\"([^\"]+).*', '\\1', x)
 #[1] "hop"

or

 sub('[^\"]+(\"[^\"]+.).*', '\\1', x)
 #[1] "\"hop\""

\"not required since "it will work too

 sub('[^"]*("[^"]*.).*', '\\1', x)
 #[1] "\"hop\""

, @AvinashRaj, sub . , stringi,

 library(stringi)
 stri_extract_all_regex(x1, '"[^"]*"')[[1]]
 #[1] "\"hop\""  "\"hop2\""

 x <- "myFunction(arg1=\"hop\",arg2=TRUE)"
 x1 <- "myFunction(arg1=\"hop\",arg2=TRUE arg3=\"hop2\", arg4=TRUE)"
+10

You can try:

str='myFunction(arg1=\"hop\",arg2=TRUE)'

gsub('.*(\\".*\\").*','\\1',str)
#[1] "\"hop\""
+3
source
x <- "myFunction(arg1=\"hop\",arg2=TRUE)"
unlist(strsplit(x,'"'))[2]
# [1] "hop"
+1
source

All Articles