R regular expressions: unexpected behavior of "[:digit:]"

I'd like to extract elements beginning with digits from a character vector but there's something about POSIX regular expression syntax that I don't understand.

I would think that

vec <- c("012 foo", "305 bar", "other", "notIt 7") grep(pattern="[:digit:]", x=vec) 

would return 1 2 4 since they are the four elements that have digits somewhere in them. But in fact it returns 3 4.

Likewise grep(pattern="^0", x=vec) returns 1 as I would expect because element 1 starts with a zero. However grep(pattern="^[:digit:]", x=vec) returns integer(0) whereas I would expect it to return 1 2 since those are the elements that start with digits.

How am I misunderstanding the syntax?

1

3 Answers

Try

grep(pattern="[[:digit:]]", x=vec) 

instead as the 'meta-patterns' between colons usually require double brackets.

7

Another solution

grep(pattern="\\d", x=vec) 
1
man 7 regex 

Within a bracket expression, the name of a character class enclosed in "[:" and ":]" stands for the list of all characters belonging to that class. Standard character class names are:

 alnum digit punct alpha graph space blank lower upper cntrl print xdigit 

Therefore a character class that is the sole member of a bracket expression will look like double-brackets, such as [[:digit:]]. As another example, consider that [[:alnum:]] is equivalent to [[:alpha:][:digit:]].

10

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

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

You Might Also Like