How to use grep()/gsub() to find exact match
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
How to find the exact match in for loop using gsub?
Use word boundaries \\b
gsub("\\bjava\\b", "xx", c("my java is", "this javascript is"))
#[1] "my xx is" "this javascript is"
You probably want
ll <- as.list(data$word)
data$new <- data$description
for(i in seq_len(nrow(data))) for(j in seq_along(ll)) {
data$new[i] <- gsub(paste0("\\b", ll[j], "\\b"), "xx", data$new[i],ignore.case = T)
}
How do I do an exact string match using gsub in R?
Use anchors instead here to match the entire string:
sub('^MOUNTAIN$', 'MOUNTAIN VIEW', raw, ignore.case = TRUE)
# [1] "MOUNTAIN VIEW" "MOUNTAIN VIEW"
If you desire, you can also use a capturing group and backreference it inside the replacement call:
sub('^(MOUNTAIN)$', '\\1 VIEW', raw, ignore.case = TRUE)
R: Find files containing exact string match followed only by _ (ignore case)
To improve the previous answer ... assuming that your file names are standard, first split the input using strsplit
and extract the Seed number, then use grepl
as suggested.
E.g.
value[grepl(paste("Seed_",as.numeric(strsplit(file, "[_|.]")[[1]][2]),"_",sep=""), value, fixed=TRUE)]
Related Topics
Getting Warning: " 'Newdata' Had 1 Row But Variables Found Have 32 Rows" on Predict.Lm
Limit Ggplot2 Axes Without Removing Data (Outside Limits): Zoom
Splitting a Continuous Variable into Equal Sized Groups
How to Use Reference Variables by Character String in a Formula
How to Calculate the Co-Occurrence in the Table
Convert Comma Separated String to Numeric Columns
How to Insert Elements into a Vector
Why Do R Objects Not Print in a Function or a "For" Loop
Conditionally Change Panel Background With Facet_Grid
Select Rows With Min Value by Group
Basic Lag in R Vector/Dataframe
R: Gsub, Pattern = Vector and Replacement = Vector
Create Group Names For Consecutive Values
R Apply() Function on Specific Dataframe Columns
Windows 7, Update.Packages Problem: "Unable to Move Temporary Installation"