Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use grep()/gsub() to find exact match

string = c("apple", "apples", "applez")
grep("apple", string)

This would give me the index for all three elements in string. But I want an exact match on the word "apple" (i.e I just want grep() to return index 1).

like image 293
Adrian Avatar asked Nov 08 '14 04:11

Adrian


People also ask

How can I get exact match in grep?

To Show Lines That Exactly Match a Search String The grep command prints entire lines when it finds a match in a file. To print only those lines that completely match the search string, add the -x option. The output shows only the lines with the exact match.

How do I check if a string has exact match?

Voting is disabled while the site is in read-only mode. Voting is disabled while the site is in read-only mode. Bookmarking is disabled while the site is in read-only mode.

How do you use exact match in JavaScript?

We can use the JavaScript string instance's match method to search for a string that matches the given pattern. to call match with a regex that matches the exact word. ^ is the delimiter for the start of the word. And $ is the delimiter for the end of the word.


2 Answers

Use word boundary \b which matches a between a word and non-word character,

string = c("apple", "apples", "applez")
grep("\\bapple\\b", string)
[1] 1

OR

Use anchors. ^ Asserts that we are at the start. $ Asserts that we are at the end.

grep("^apple$", string)
[1] 1

You could store the regex inside a variable and then use it like below.

pat <- "\\bapple\\b"
grep(pat, string)
[1] 1
pat <- "^apple$"
grep(pat, string)
[1] 1

Update:

paste("^",pat,"$", sep="")
[1] "^apple$"
string
[1] "apple"   "apple:s" "applez" 
pat
[1] "apple"
grep(paste("^",pat,"$", sep=""), string)
[1] 1
like image 103
Avinash Raj Avatar answered Oct 28 '22 22:10

Avinash Raj


For exact matching, it makes the most sense to use ==. Additionally, this will be faster than grep(), and is obviously much easier.

which(string == "apple")
# [1] 1
like image 39
Rich Scriven Avatar answered Oct 28 '22 23:10

Rich Scriven