Message-ID: <ldirof$npj$1@ger.gmane.org>
Date: 2014-02-13T16:27:08Z
From: Keith Jewell
Subject: grep for multiple pattern?
In-Reply-To: <81002AB7-F20A-44B0-86A0-627B1A2B13E5@me.com>
On 13/02/2014 15:51, Marc Schwartz wrote:
>
> On Feb 13, 2014, at 8:43 AM, Rainer M Krug <Rainer at krugs.de> wrote:
>
>> Hi
>>
>> I want to search for multiple pattern as grep is doing for a single
>> pattern, but this obviously not work:
>>
>>> grep("an", month.name)
>> [1] 1
>>> grep("em", month.name)
>> [1] 9 11 12
>>> grep("eb", month.name)
>> [1] 2
>>> grep(c("an", "em", "eb"), month.name)
>> [1] 1
>> Warning message:
>> In grep(c("an", "em", "eb"), month.name) :
>> argument 'pattern' has length > 1 and only the first element will be used
>>>
>>
>> Is there an equivalent which returns the positions as grep is doing, but
>> not using the strict full-string matching of match()?
>>
>> I could obviously do:
>>
>>> unlist( sapply(pat, grep, month.name ) )
>> an em1 em2 em3 eb
>> 1 9 11 12 2
>>
>> but is there a more compact command I am missing?
>>
>> Thanks,
>>
>> Rainer
>
>
> The vertical bar '|' acts as a logical 'or' operator in regex expressions:
>
>> grep("an|em|eb", month.name)
> [1] 1 2 9 11 12
>
>> grep("an|em|eb", month.name, value = TRUE)
> [1] "January" "February" "September" "November" "December"
>
>
> Regards,
>
> Marc Schwartz
>
and if you want your patterns in a vector
> pat <-c("an", "em", "eb")
> grep(paste(pat, collapse="|"), month.name)
[1] 1 2 9 11 12