Home > Mobile >  Using multiple regex patterns in the same function [duplicate]
Using multiple regex patterns in the same function [duplicate]

Time:10-03

I'm using regex in r and since sometimes a pattern can become pretty big and complex, I'd like to use multiple patterns instead of one in the same function

as an example:

pattern1 <- "x"
pattern2 <- "y"

but I can only use one in a given function like:

str_view_all(string, pattern1)

is there anyway I could use pattern1 and pattern2 together in lets say str_view_all()?

it would also be real nice if I could tell the r that in case of conflicts one pattern may overrule the other.

CodePudding user response:

You can combine patterns in regex directly I think, with something like x|y . Let's say (x)|(y). With str_extract it will find first match (corresponding to x pattern if first match pattern x, y instead) whereas str_extract_all will find all matches for both and then you will be able to choose which one you want to keep. Maybe take a look and test your pattern here https://regex101.com

'Lucy in the sky' -> string
str_view_all(string, 'Lucy|sky')

Lucy in the sky

str_extract(string, 'Lucy|sky')

Lucy, not sky

[1] "Lucy"
str_extract_all(string, 'Lucy|sky')

A list

[[1]]
[1] "Lucy" "sky" 

A vector

str_extract_all(string, 'Lucy|sky') %>% purrr::flatten_chr()
[1] "Lucy" "sky" 

And f you have multiple candidates in the string:

'Lucy in the sky because Lucy loves the Beatles' -> string
str_extract_all(string, 'Lucy|sky')
str_extract(string, 'Lucy|sky')

CodePudding user response:

You can include all the pattern in one vector, combine them using | and use it in str_view_all.

all_pattern <- c(pattern1, pattern2)
str_view_all(string, str_c(all_pattern, collapse = '|'))
  • Related