Home > Blockchain >  grep search for the exact pattern in R
grep search for the exact pattern in R

Time:11-15

I want to search for the exact match string. I am able to find it but, I don't want a match if the string contains additional details appended to the pattern. For example, in below code I am able to find the match

grep("CUST CODE: 123", x = "CUST CODE: 123")
[1] 1

But, I don't want below string to get matched or it should avoid the match since there is ADDITIONAL after 123.

grep("CUST CODE: 123", x = "CUST CODE: 123 ADDITIONAL")

I have used options like ignore.case, Fixed but, that leads matching.

CodePudding user response:

You may place starting ^ and ending $ anchors around the pattern:

x <- c("CUST CODE: 123", "CUST CODE: 123 ADDITIONAL")
grep("^CUST CODE: 123$", x, value=TRUE)

[1] "CUST CODE: 123"
  •  Tags:  
  • r
  • Related