Home > Mobile >  Detect substring within a string while not considering part of the substring
Detect substring within a string while not considering part of the substring

Time:09-16

I'm trying to check whether string B is contained by string A and this is what I tried:

library(stringr)
string_a <- "something else free/1a2b a bird yes"
string_b <- "free/xxxx a bird"
str_detect(string_a, string_b)

I would expect a match (TRUE) since I wouldn't like to consider part of string_b followed by the "/" and before a white space, which is why I put "/xxxx".

In a way the "/xxxx" should represent match any string or number possible in these places. Is there maybe another notation to ignore parts of string when matching like this?

CodePudding user response:

Yes, in regex you can use .* to match zero or more characters.

library(stringr)
string_a <- "something else free/1a2b a bird yes"
string_b <- "free/xxxx a bird"
string_c <- "free/.*a bird"

str_detect(string_a, string_c)
#[1] TRUE

If you cannot change string_b at source, you may use str_replace_all or gsub to replace xxxx with '.*'.

str_detect(string_a, str_replace_all(string_b, 'x ', '.*'))
#[1] TRUE
  • Related