How to grep with fixed=T
, but only at the beginning of the string?
grep("a.", c("a.b", "cac", "sss", "ca.f"), fixed = T)
# 1 4
I would like to get only the first occurrence. [Edit: the string to match is not known in advance, and can be anything. "a." is just for the sake of example]
Thanks.
[Edit: I sort of solved it now, but any other ideas are highly welcome. I will accept as an answer any alternative solution.
s <- "a."
res <- grep(s, c("a.b", "cac", "sss", "ca.f"), fixed = T, value = T)
res[substring(res, 1, nchar(s)) == s]
]
Use the ^ (caret) symbol to match expression at the start of a line. In the following example, the string kangaroo will match only if it occurs at the very beginning of a line. Use the $ (dollar) symbol to match expression at the end of a line.
fixed = TRUE just tells grep there is no regular expression in the pattern . fixed=TRUE means that the pattern shouldn't be considered a regex , but just as it is. Your vector contains the substring YES and so the match.
grep() function in R Language is used to search for matches of a pattern within each element of the given string. Parameters: pattern: Specified pattern which is going to be matched with given elements of the string.
The grepl() stands for “grep logical”. In R it is a built-in function that searches for matches of a string or string vector. The grepl() method takes a pattern and data and returns TRUE if a string contains the pattern, otherwise FALSE.
If you want to match an exact string (string 1) at the beginning of the string (string 2), then just subset your string 2 to be the same length as string 1 and use ==, should be fairly fast.
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