Using gsub, you can use the \G
function, an anchor that can match in one of two positions.
x <- 'foo123bar123baz123456abc1111def123456789' gsub('(?:\\d+|\\G(?<!^)\\D*)\\K\\d*', '', x, perl=T)
Explanation
(?:
Alternatively, you can use the optional group:
gsub('(?:^\\D*\\d+)?\\K\\d*', '', x, perl=T)
Another way that I find useful and does not require (*SKIP)(*F)
verbs backtracking or \G
and \K
is to use alternation in the context of placing what you want to combine in the capture group on the left side, and put something what you want to exclude on the right side (saying throw it away, this is trash ...)
gsub('^(\\D*\\d+)|\\d+', '\\1', x)
source share