Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace all characters except expression using gsub only

Tags:

regex

r

gsub

Given strings:

smple_paths <- c("/path/path/path/abc22/path/path",
                 "/apath/apath/paath/abc11/something/path")

I would like to replace all characters excluding phrase abc\\d{2}

Attempt

gsub(
    pattern = "(?!abc\\d{2})",
    replacement = "",
    x = smple_paths,
    perl = TRUE
)

# [1] "/path/path/path/abc22/path/path"        
# [2] "/apath/apath/paath/abc11/something/path"

Desired results

abc22
abc11

Notes

  • I'm not looking for stringr::str_extract based solution or any other solution not based on gsub
like image 500
Konrad Avatar asked Sep 12 '26 14:09

Konrad


1 Answers

If you do not care about the abc\d{2} context, you may use

sub(".*(abc\\d{2}).*", "\\1", smple_paths)

See this regex demo and this R demo.

If you care about the context, you may match and capture abc + 2 digits after / and before / or end of the string, while matching any text before and after this pattern using

 sub("^.*/(abc\\d{2})(?:/.*)?$", "\\1", smple_paths)

See the R demo and a regex demo.

Details

  • ^ - start of the string (not necessary here, but kept for the sake of clarity)
  • .* - any 0+ chars, as many as possible
  • / - a / char
  • (abc\\d{2}) - Group 1: abc and 2 digits
  • (?:/.*)? - an optional (1 or 0) occurrence of a / followed with any 0+ chars as many as possible
  • $ - end of string.

The \1 placeholder in the replacement pattern inserts the captured text back into the result.

like image 57
Wiktor Stribiżew Avatar answered Sep 15 '26 03:09

Wiktor Stribiżew



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!