a <- "quick brown fox"
b <- "quick brown dog"
I want to know if both the "quick" AND "fox" strings exist in a,b.
i.e., applying the answer to this question on,
a - should return TRUE
b - should return FALSE
a <- "quick brown fox"
b <- "quick brown dog"
I want to know if both the "quick" AND "fox" strings exist in a,b.
i.e., applying the answer to this question on,
a - should return TRUE
b - should return FALSE
We can use a double grepl
with &
(more safer)
grepl('quick', a) & grepl('fox', a)
#[1] TRUE
grepl('quick', a) & grepl('fox', b)
#[1] FALSE
Or if we know the position of 'fox' beforehand, i.e. if it follows after quick
(as in the example), then we can use a regex 'quick' followed by 0 or more characters followed by 'fox'. We may also flank it with word boundary (\\b
) to avoid surprises i.e. to avoid matching words like quickness
or foxy
.
grepl('.*\\bquick\\b.*\\bfox\\b', a)
#[1] TRUE
grepl('.*\\bquick\\b.*\\bfox\\b', b)
#[1] FALSE
As I mentioned earlier, this will give FALSE
for foxy
grepl('.*\\bquick\\b.*\\bfox\\b', 'quick brown foxy')
#[1] FALSE
If the position varies,
grepl('.*\\bquick\\b.*\\bfox\\b|.*\\bfox\\b.*\\bquick\\b', b)
#[1] FALSE
grepl('.*\\bquick\\b.*\\bfox\\b|.*\\bfox\\b.*\\bquick\\b', a)
#[1] TRUE