Regular Expression to Match EXACTLY Any Number of Characters in R

r, regex

Solution

To match the character "a" occuring exactly twice, you could use a negative lookbehind combined with a negative lookahead. I.e., you look for a position that

- does NOT follow a character "a",

- contains the string "aa" and

- is NOT followed by an "a"

The regex for that is `(?<!a)a{2}(?!a)`.

Example:

test <- c("baa", "aaaa", "aab", "aa", "bbba", "bbaabbb")
grep("(?<!a)a{2}(?!a)", test, perl = TRUE, value = TRUE)
# [1] "baa"     "aab"     "aa"      "bbaabbb"

Matching the character "b" occuring exactly three times is done analogously:

grep("(?<!b)b{3}(?!b)", test, perl = TRUE, value = TRUE)
# [1] "bbba"    "bbaabbb"

Problem

I want to count the number of exact consecutive occurrence of characters using regex. Let the patterns be `"aa"` and `"bbb"` say, i.e. the number of times `"a"` occurs exactly twice and consecutively; `"b"` occurs exactly thrice and consecutively (they can be bounded before and after by any character including nothing except by the character itself). If the test vector is ``` c("baa", "aaaa", "aab", "aa", "bbba", "bbaabbb") ``` the result for the counts should be as follows: The patterns matching `"aa"` being `c("baa", "aab", "aa", "bbaabbb")` & The patterns matching `"bbb"` being `c("bbba", "bbaabbb")` I have used `"\\<"` & `"\\>"` but it doesn't quite give me the result I want. I would appreciate any assistance.

Original source