2

This is a bare minimal example of a larger more complex dataset, just trying to get my head around something.

> grep("X10\\.1+",c("X10.10","X10.11","X10.12"))
[1] 1 2 3

Now I would have expected only 2 to have been returned, since '+' is supposed to be '1 or more of the preceding element'. I thought escaping the period (which I have to deal with so want to keep it in the example) could have been causing the issue.

> grep("X101+",c("X1010","X1011","X1012"))
[1] 1 2 3

So, my understanding of the functionality of '+' is wrong?

CONCLUSION:

Thanks @James. So my understanding was the + was 'ANOTHER 1 or more of the preceding element' as opposed to what it actually means, which is 'JUST 1 or more of the preceding element'.

11+ would have done what I was thinking (having an ADDITIONAL 1 or more 1's after the first 1 etc). Cheers

2
  • hi, can you explain why you expect only 2 to have been returned?
    – Nikos
    Dec 13, 2012 at 1:30
  • Hi Nikos. I'd expect only 2 based on the my understanding of + which is 1 or more of the preceding element. So 1+ should be TRUE for 11 or 111 or 1111 but not for 10 or 12 etc as 0 is a different character to 1.
    – nzcoops
    Dec 13, 2012 at 3:06

2 Answers 2

6

You need to signify that after any number of 1s, you want to match the end of the string. You use $ to do this.

grep("X10\\.1+$",c("X10.10","X10.11","X10.12"))
[1] 2

Similarly, ^ matches the start of the string if you want to restrict that the match starts X10., rather than PX10. for instance which would be matched by the existing regex.

6
  • Thanks James. I had toyed around with $. What I don't get is that + is 1 or more of the preceding right? Not zero or more. So, X10.10 should be a false because there isn't AT LEAST another 1 after the first one. I could understand what you're saying if it was picking up X10.110 as a true but picking up X10.10 still seems wrong to me.
    – nzcoops
    Dec 13, 2012 at 3:11
  • I'm not saying I think you're wrong :) I'd have thought if using an * you might pick up 1 2 and 3, but surely a + requires it to have a .11 regardless of the use of $?
    – nzcoops
    Dec 13, 2012 at 3:12
  • 1
    No, + means one or more instances of the symbol, including the original one, ie 1+ is a single entity meaning one or more 1.
    – James
    Dec 13, 2012 at 7:33
  • +rep, why does he need to match the end of the string with $
    – Nikos
    Dec 13, 2012 at 12:09
  • 2
    @Nikos Because otherwise it matches on strings where the pattern is included, which is the problem the OP is posting.
    – James
    Dec 13, 2012 at 12:58
2

In this case, the preceding element is the digit '1' which is present at that position in all 3 elements. Your prior understanding of '+' is correct.

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.