0
gsub("([a-z]+)([0-9]+)","\\2","ytu678yu")
[1] "678yu"
gsub("([a-z]+)([0-9]+)(.*)","\\2","ytu678yu")
[1] "678"

I wonder why gsub("([a-z]+)([0-9]+)","\\2","ytu678yu") can not get 678?

1
  • Should this have been asked in a comment to your earlier question here?
    – flodel
    Oct 20, 2012 at 11:56

1 Answer 1

3

In the first case, the pattern matches "ytu678" and then this is replaced by "\2" ie "678", so finally you get "678yu".

In the second case, the pattern matches "ytu678yu" and then this is replaced by "\2" ie "678", so finally you get "678".

Try this:

> gsub("([a-z]+)([0-9]+)","","ytu678yu")
[1] "yu"
> gsub("([a-z]+)([0-9]+)(.*)","","ytu678yu")
[1] ""
1
  • 1
    As another example, if the OP just wants the numbers from the string, gsub("[a-z]+","","ytu678yu"). +1 Oct 20, 2012 at 4:12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.