简体   繁体   中英

Find part of string in another string

How do I find a part of a string in another string. Below you can find some sample data:

a <- c("23,45,24,67,91,10")
b <- c("as.01,as.23,as55,as69")

The objective is to find any substring of a in b . Thus this should return TRUE since 23 is present in a and in b . I already tried functions such as

charmatch
grepl
match 

But all of these do not seem to fit my purpose. Any help is appreciated!

There may be an error in your inputs a and b:

a <- c("23","45","24","67","91","10")
b <- c("as.01","as.23","as55","as69")

> any(sapply(a, grepl, x=b))
[1] TRUE

Or only in your input a:

a <- c("23","45","24","67","91","10")
b <- c("as.01,as.23,as55,as69")

> any(sapply(a, grepl, x=b))
[1] TRUE

Or if no error:

> any(sapply(strsplit(a,',')[[1]], grepl, x=b))
[1] TRUE

You can avoid *apply loops and vectorize it using gsub in order to replace , to | and convert it to a valid regex expression.

grepl(gsub(",", "|", a, fixed = TRUE), b)
## [1] TRUE

This way, you also don't need to use any as it will return only one TRUE even if you have more than one matches, for example.

a <- "23,45,55,67,91,10"
b <- "as.01,as.23,as55,as69"

grepl(gsub(",", "|", a, fixed = TRUE), b)
## [1] TRUE

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM