Home > Mobile >  Extract Elements From a String Using Regular Expressions
Extract Elements From a String Using Regular Expressions

Time:10-11

I have the following string:

x <- "DevicePool1/Device1/Measurements/20210910231005/event.csv"

how can I retrieve Device1 out of this string in R ?

CodePudding user response:

Try any of these. The first 4 also work if x is a character vector such that each element stores a path, e.g. x <- c(x, x). No packages are used.

read.table(text = x, sep = "/", fill = TRUE)[[2]]

sub(".*?/(.*?)/.*", "\\1", x)

gsub("^.*?/|/.*", "", x, perl = TRUE)

sapply(strsplit(x, "/"), `[`, 2)

scan(text = x, sep = "/", what = "", quiet = TRUE)[2]

CodePudding user response:

Should work in your case from stringr package

x <- "DevicePool1/Device1/Measurements/20210910231005/event.csv"
unlist(str_split(x, "/"))[2]

CodePudding user response:

You can use a regular expression

> gsub(".*/(.*?)/.*","\\1",x)
[1] "Device1"

.* means any character appearing 0 or more times and /(.*?)/is your pattern

CodePudding user response:

Another one using regexpr and regmatches with look behind for / using (?<=/) and look ahead for / using (?=/) and get the non greedy match in between with .*? or everything but not / using [^/]*.

regmatches(x, regexpr("(?<=/).*?(?=/)", x, perl=TRUE))
#regmatches(x, regexpr("(?<=/)[^/]*(?=/)", x, perl=TRUE)) #Alternative
#[1] "Device1"

Or using [^/]* in sub

sub("[^/]*/([^/]*)/.*", "\\1", x)
#sub("/.*", "", sub("[^/]*/", "", x)) #Alternative
#gsub("^[^/]*/|/.*", "", x) #Alternative
#[1] "Device1
  •  Tags:  
  • r
  • Related