I don't quite understand why this doesn't result in "test"
and would appreciate an explanation:
a = "blah test"
sub('^.*(test|$)', '\\1', a)
# [1] ""
Compare it to the sed
expression:
echo 'blah test' | sed -r 's/^.*(test|$)/\1/'
# test
echo 'blah blah' | sed -r 's/^.*(test|$)/\1/'
#
Fwiw, the following achieves what I want in R (and is equivalent to the above sed
results):
sub('^.*(test)|^.*', '\\1', a)
You need to mark the ^.*
as non-greedy
> sub('^.*?(test|$)', '\\1', "blah test")
[1] "test"
> sub('^.*?(test|$)', '\\1', "blah blah")
[1] ""
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With