Home > Enterprise >  Is there to remove part of string with exception in R
Is there to remove part of string with exception in R

Time:10-13

library(stringr)

I have some text that I want to clean up using string_remove_all but I dont seem to get the expected results. I want to remove all other suffixes except the strings with _other

# Test text
testregex <- c("d1_1", "d2_other", "d1_1_2", "test", "d5_extra", "a22_10")

# Code 
str_remove_all(testregex, "_[^other]")

# Expected results

expected <- c("d1", "d2_other", "d1", "test", "d5", "a22")

CodePudding user response:

You can use sub with a negative look ahead for _other with (?!_other) and remove everything from _ with _.*.

sub("(?!_other)_.*", "", testregex, perl=TRUE)
#stringr::str_remove_all(testregex, "(?!_other)_.*") #Alternative
#[1] "d1"       "d2_other" "d1"       "test"     "d5"       "a22"
  • Related