Apply condition to opposite of regex pattern

How could I apply this regex so that all data in the column that does not match this regex turns to ‘Need’ – Currently, if I run this, it applies Need to all that match the regex. The regex pattern should reflect ‘A-1234567’ – Bonus: is there a way to ignore case for the first letter as well. Thank you.

df %>% 
  mutate(`Col2` = str_replace_all(df$`Col2`,'[[:alpha:]]{1}[[:punct:]]{1}[0-9]{7}','Need'))

>Solution :

Try this:

df %>% 
  mutate(Col2 = if_else(grepl('[[:alpha:]]{1}[[:punct:]]{1}[0-9]{7}', Col2),
                        Col2, 'Need'))

Leave a Reply