R mask for grep to search for duplicate words

I just want to find lines with the repeated word HALL (more than once). For example, "HALL #1 HALL #2 HALL #3" . I tried to use

 grepl("HALL{2,}", "HALL #1 HALL #2 HALL #3") 

but grepl returned FALSE . What am I doing wrong?

+6
source share
3 answers

{2,} means the coincidence of characters in front of him for two or more times. Therefore, if you want to match the HALL pattern, you need to put parentheses around it, and it also seems that you do not mean the consistent HALL pattern, so you need to substitute the pattern a little. The following should do the job:

 grepl("(.*HALL.*){2,}", "HALL #1 HALL #2 HALL #3") [1] TRUE 
+1
source

You can use stringr ,

 str_count("HALL #1 HALL #2 HALL #3", 'HALL')>1 #[1] TRUE 
+3
source

You can use (?:.*?HALL.*?){2,} :

 grepl("(?:.*?HALL.*?){2,}", "HALL #1 HALL #2 HALL #3") #[1] TRUE 

Here is a breakdown of the above regex.

+3
source

All Articles