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).
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.
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.
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.
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With