Q:

Remove spaces between greater than signs

I have a string like this:
foo > bar > foo bar > foo > test > test this

I would like to take any strings within the greater than signs and convert them into single words with no space between them but preserve all other spaces like this:
foo > bar > foobar > foo > test > testthis

I've tried using gsub to remove whitespace gsub(" ", "", x, fixed = TRUE), but I am not sure how to do this only within the greater than signs while preserving the spaces next to the greater than signs

A:

One option would be a PCRE SKIP/FAIL by matching zero or more space (\\s*) followed by > followed by zero or more spaces (\\s*).   At the (*SKIP), it no longer goes back to the right of the match nor retry it.   The (*FAIL) forces the pattern to FAIL until the left of (*SKIP) while it matches the space characters (|\\s+) right of the ((*FAIL)) and replace it with blank ("")
gsub("\\s*\\>\\s*(*SKIP)(*FAIL)|\\s+", "", str1, perl = TRUE)
#[1] "foo > bar > foobar > foo > test > testthis"

Or another option is to match space between two word characters.   Here the spaces are matched between a positive regex lookbehind word character ((? <=\\w)) and a positive lookahead word character or at the end of the string ((? =\\w|\\$))
gsub("(?<=\\w)\\s(?=\\w|\\$)", "", str1, perl = TRUE)
#[1] "foo > bar > foobar > foo > test > testthis"

Or without using regex lookarounds, we can capture the word
gsub("(\\w)\\s(\\w)", "\\1\\2", str1)
#[1] "foo > bar > foobar > foo > test > testthis"

data
str1 <- "foo > bar > foo bar > foo > test > test this"

