Getting only the matched part of the string in R

Is there a function in R that matches a regular expression and returns only matched parts? Something like this grep -o, therefore:

> ogrep('.b.',c('abc','1b2b3b4'))
[[1]]
[1] abc

[[2]]
[1] 1b2 3b4
+3
source share
4 answers

You should probably give Gabor Grothendieck a check to write the gsubfn package:

 require(gsubfn)
#Loading required package: gsubfn
 strapply(c('abc','1b2b3b4'), ".b.", I)

#Loading required package: tcltk
#Loading Tcl/Tk interface ... done
[[1]]
[1] "abc"

[[2]]
[1] "1b2" "3b4"

It just applies the identity function i to the pattern matches.

+6
source

Try stringr:

library(stringr)
str_extract_all(c('abc','1b2b3b4'), '.b.')
# [[1]]
# [1] "abc"
# 
# [[2]]
# [1] "1b2" "3b4"
+7
source

gregexpr , :

> s = c('abc','1b2b3b4')
> m = gregexpr('.b.',s)
> substring(s[1],m[[1]],m[[1]]+attr(m[[1]],'match.length')-1)
[1] "abc"
> substring(s[2],m[[2]],m[[2]]+attr(m[[2]],'match.length')-1)
[1] "1b2" "3b4"

"m" . s, .

+5

, regmatches !

x <- c('abc','1b2b3b4')
regmatches(x, gregexpr('.b.', x))

# [[1]]
# [1] "abc"

# [[2]]
# [1] "1b2" "3b4"

, regmatches ?

+5

Source: https://habr.com/ru/post/1782285/


All Articles