Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inverting a regex in R

Tags:

regex

r

stringr

I have this string:

[1] "19980213"    "19980214"    "19980215"    "19980216"    "19980217"    "iffi"        "geometry"   
[8] "date_consid"

and I want to match all the elements that are not dates and not "date_consid". I tried

res =  grep("(?!\\d{8})|(?!date_consid)", vec, value=T)

But I just cant make it work...

like image 681
Robin Kohrs Avatar asked Dec 30 '22 17:12

Robin Kohrs


1 Answers

You can use

vec <- c("19980213", "19980214", "19980215", "19980216","19980217", "iffi","geometry", "date_consid")
grep("^(\\d{8}|date_consid)$", vec, value=TRUE, invert=TRUE)
## => [1] "iffi"     "geometry"

See the R demo

The ^(\d{8}|date_consid)$ regex matches a string that only consists of any eight digits or that is equal to date_consid.

The value=TRUE makes grep return values rather than indices and invert=TRUE inverses the regex match result (returns those that do not match).

like image 96
Wiktor Stribiżew Avatar answered Jan 13 '23 16:01

Wiktor Stribiżew