Is it possible to use an AND operator in grepl()?

Mus picture Mus · Jul 28, 2017 · Viewed 9k times · Source

I want to search for anything that begins with 55 and anything that has the word Roof (case-sensitive, for those who are curious) in it.

So far I have been unsuccessful, as I can only seem to use the OR operator:

grepl("*^55|*Roof", dataset$longname)

Ultimately, I want to achieve something like this:

grepl("*^55&&*Roof", dataset$longname)

or

grepl("*^55&*Roof", dataset$longname)

(Clearly, neither of these work - they're for illustration only.)

I want my results to show anything that begins with 55 and which has the word Roof anywhere in it.

For example, I would expect both of these results to be picked up by the grepl() function:

55 - Roof Structure

and

55-Wall to Roof

Is there an AND operator that can be used with grepl()?

Answer

G. Grothendieck picture G. Grothendieck · Jul 28, 2017

To search for a string having both "a" and "b"

grepl("a", x) & grepl("b", x)

or

grepl("a.*b|b.*a", x)

If we know the order of the two parts then we can omit one of the two halves of the last grepl. For example, in the case of the query in the question this would be sufficient to find a string that starts with 55 and contains Roof

grepl("^55.*Roof", x)