0
> x<-c("01.mp3","invite.mp3")
> x[grep(x,pattern="[:digit:]")]
[1] "invite.mp3"

In the regular expression,Why i can not get "01.mp3"?

alexwhan
  • 15,636
  • 5
  • 52
  • 66
showkey
  • 482
  • 42
  • 140
  • 295
  • see [this SO question](http://stackoverflow.com/questions/11525408/r-regular-expressions-unexpected-behavior-of-digit) for a discussion and links to explanations of why it doesn't work. What will work is `x[grep(x,pattern="[[:digit:]]")]` or `x[grep(x,pattern="[0-9]")]` – Jota Nov 27 '13 at 05:03

2 Answers2

2

If you want to get "01.mp3" because it consists of two digits and ".mp3", then you could do something like:

x<-c("01.mp3","invite.mp3")
x[grep(x,pattern="[0-9]{2}.mp3")]
wind
  • 313
  • 4
  • 7
0

I think what's happening here (and someone will presumably correct me), is that you are not actually matching what you think you are. You need to put the bracket list [:digit:] inside brackets to match the list, otherwise you are matching the literal characters in :digit:. You can see this by adding a third element to x:

x<-c("01.mp3","invite.mp3", ":")
x[grep(pattern="[:digit:]", x = x)]
#[1] "invite.mp3" ":"  

So [:digit] will match : as well. If instead, you use [[:

x[grep(x,pattern="[[:digit:]]")]
#[1] "01.mp3"     "invite.mp3"

you are then matching the class digit.

alexwhan
  • 15,636
  • 5
  • 52
  • 66