I have a string:
str1 <- \"This is a string, that I\'ve written
to ask about a question, or at least tried to.\"
How would
The general problem of mathcing text requires regular expressions. In this case you just want to match specific characters, but the functions to call are the same. You want gregexpr.
matched_commas <- gregexpr(",", str1, fixed = TRUE)
n_commas <- length(matched_commas[[1]])
matched_ion <- gregexpr("ion", str1, fixed = TRUE)
n_ion <- length(matched_ion[[1]])
If you want to only match "ion" at the end of words, then you do need regular expressions. \b represents a word boundary, and you need to escape the backslash.
gregexpr(
"ion\\b",
"ionisation should only be matched at the end of the word",
perl = TRUE
)