suppressPackageStartupMessages(library("tidyverse"))
package 㤼㸱tidyverse㤼㸲 was built under R version 3.6.3
(.)\1\1
: The same character appearing three times in a row. E.g. "aaa"
"(.)(.)\\2\\1"
: A pair of characters followed by the same pair of characters in reversed order. E.g. "abba"
.(..)\1
: Any two characters repeated. E.g. "a1a1"
."(.).\\1.\\1"
: A character followed by any character, the original character, any other character, the original character again. E.g. "abaca"
, "b8b.b"
."(.)(.)(.).*\\3\\2\\1"
: Three characters followed by zero or more characters of any kind followed by the same three characters but in reverse order. E.g. "abcsgasgddsadgsdgcba"
or "abccba"
or "abc1cba"
.1. Start and end with the same character.
str_subset(words, "^(.)((.*\\1$)|\\1?$)")
[1] "a" "america" "area" "dad" "dead" "depend" "educate"
[8] "else" "encourage" "engine" "europe" "evidence" "example" "excuse"
[15] "exercise" "expense" "experience" "eye" "health" "high" "knock"
[22] "level" "local" "nation" "non" "rather" "refer" "remember"
[29] "serious" "stairs" "test" "tonight" "transport" "treat" "trust"
[36] "window" "yesterday"
2. Contain a repeated pair of letters (e.g. church contains ‘ch’ repeated twice.)
str_subset("church", "([A-Za-z][A-Za-z]).*\\1")
[1] "church"
Now, find all matching words in words.
str_subset(words, "([A-Za-z][A-Za-z]).*\\1")
[1] "appropriate" "church" "condition" "decide" "environment" "london"
[7] "paragraph" "particular" "photograph" "prepare" "pressure" "remember"
[13] "represent" "require" "sense" "therefore" "understand" "whether"
The \\1
pattern is called a backreference. It matches whatever the first group matched. This allows the pattern to match a repeating pair of letters without having to specify exactly what pair letters is being repeated.
Note that these patterns are case sensitive. Use the case insensitive flag if you want to check for repeated pairs of letters with different capitalization.
3. Contain one letter repeated in at least three places (e.g. eleven contains three e’s.)
First, check that regex works with th example given in the question.
str_subset("eleven", "([a-z]).*\\1.*\\1")
[1] "eleven"
Now, retrieve the matching words in words.
str_subset(words, "([a-z]).*\\1.*\\1")
[1] "appropriate" "available" "believe" "between" "business" "degree"
[7] "difference" "discuss" "eleven" "environment" "evidence" "exercise"
[13] "expense" "experience" "individual" "paragraph" "receive" "remember"
[19] "represent" "telephone" "therefore" "tomorrow"