RegEx to exclude number that begin with some pattern

135 Views Asked by At

I have the following list of numbers:

5501, 534, 234, 550, 5500

I want to select all numbers except "5501" and "5500" and use it with the stringr package in R. I tried the following expression without luck:

^((?!550)\d)*$ 
3

There are 3 best solutions below

0
On BEST ANSWER

Try this regex:

^((?!5501|5500)[0-9]*)$

Observe “Negative Lookahead” command ?! in the above regex. This will exclude 5501 and 5500

Hope this helps

0
On

We can use grep

v1[grep("^.{3}$", v1)]
#[1] 534 234 550

Or more specifically

v1[grep("^550[01]$", v1, invert=TRUE)]
#[1] 534 234 550

data

v1 <-  c(5501, 534, 234, 550, 5500)
4
On

If there are only those two exact strings that you want to eliminate (and never 5502 for example) you could use standard R subsetting, there is no need to use regex.

x <- c(5501, 534, 234, 550, 5500)
x <- x[x != 5500 & x != 5501]

If instead you care about all values that start with 550 but not those which might have 550 somewhere else you could use

x<-x[stringi::stri_sub(x, 1,3) != "550"  | x == "550"]