Home > database >  Grep for a character in one element of a vector
Grep for a character in one element of a vector

Time:12-04

Unless I am overlooking something, I cannot find the solution to the following.

If I have the following single element vector:

c("133 45123; 4514;25")

How can I find the position within this element that has the ";" and " ", such that I can then use substr to obtain:

45123;

Have tried grep, but that seems to work over a vector of multiple elements.

CodePudding user response:

x <- c("133 45123; 4514;25")

stringr::str_extract(x, "\\w (?=; )")
[1] "45123"

In Base R:

sub(".*?(\\w ); .*", "\\1", x)
[1] "45123"

or even:

regmatches(x, regexpr("\\w (?=; )", x, perl = TRUE))
[1] "45123"

CodePudding user response:

Strsplit() will do it. Knew I was overlooking something.

  • Related