johnsonzhj johnsonzhj - 11 months ago 46
R Question

How to extract the cases with certain characters

I want to ask a question about regular expression. I want to extract the cases that include only the certain characters.
For example, in the following vector, I want to extract the cases that only include A or B.


What I expect to get is the following, how I can achieve this?


Answer Source


d[!grepl('[^AB]', d)]

which says, exclude all the elements in d that contain anything other than "A" or "B".