Challenge - 5 Problems
Regex Master in R
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of grepl with pattern and ignore.case
What is the output of this R code snippet?
R Programming
text <- c("Apple", "banana", "Cherry", "date") result <- grepl("a", text, ignore.case = TRUE) print(result)
Attempts:
2 left
💡 Hint
grepl returns TRUE if the pattern is found in each element. ignore.case = TRUE makes it case insensitive.
✗ Incorrect
The pattern 'a' appears in 'Apple' (A), 'banana' (a), and 'date' (a) ignoring case, but not in 'Cherry'. So the result is [1] TRUE TRUE FALSE TRUE, which is option C.
❓ Predict Output
intermediate2:00remaining
Result of sub function with regex
What is the output of this R code?
R Programming
text <- "The rain in Spain" result <- sub("ain", "XXX", text) print(result)
Attempts:
2 left
💡 Hint
sub replaces only the first match of the pattern.
✗ Incorrect
The pattern 'ain' appears twice: in 'rain' and 'Spain'. sub replaces only the first occurrence, so only 'rain' changes to 'rXXX'.
🔧 Debug
advanced2:00remaining
Identify the error in regex pattern
What error does this R code produce?
R Programming
text <- "abc123" result <- grepl("[a-z{3}", text) print(result)
Attempts:
2 left
💡 Hint
Check if the regex pattern has balanced brackets.
✗ Incorrect
The pattern '[a-z{3}' is missing a closing bracket ']', so R throws an error about invalid regex.
❓ Predict Output
advanced2:00remaining
Output of regmatches with gregexpr
What is the output of this R code?
R Programming
text <- "one1 two22 three333" matches <- regmatches(text, gregexpr("\\d+", text)) print(matches)
Attempts:
2 left
💡 Hint
gregexpr finds all matches of one or more digits, regmatches extracts them.
✗ Incorrect
The pattern '\\d+' matches sequences of digits. The text has '1', '22', and '333' as digit sequences.
🧠 Conceptual
expert2:00remaining
Number of matches with lookahead in R regex
How many matches does this R code find?
R Programming
text <- "aaaa" matches <- gregexpr("a(?=a)", text, perl=TRUE) length(regmatches(text, matches)[[1]])
Attempts:
2 left
💡 Hint
Lookahead '(?=a)' matches 'a' only if followed by another 'a'.
✗ Incorrect
In 'aaaa', the pattern matches the first three 'a's because each is followed by another 'a'. The last 'a' is not followed by 'a', so total matches are 3.