0
0
R Programmingprogramming~20 mins

Regular expressions in R in R Programming - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Regex Master in R
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2: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)
A[1] FALSE TRUE TRUE TRUE
B[1] TRUE FALSE TRUE FALSE
C[1] TRUE TRUE FALSE TRUE
D[1] TRUE TRUE TRUE TRUE
Attempts:
2 left
💡 Hint
grepl returns TRUE if the pattern is found in each element. ignore.case = TRUE makes it case insensitive.
Predict Output
intermediate
2: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)
A"The rXXX in Spain"
B"The rain in SpXXX"
C"The rain in Spain"
D"The rXXX in SpXXX"
Attempts:
2 left
💡 Hint
sub replaces only the first match of the pattern.
🔧 Debug
advanced
2: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)
AError: invalid regular expression '[a-z{3}'
BSyntaxError: invalid regular expression
C[1] TRUE
D[1] FALSE
Attempts:
2 left
💡 Hint
Check if the regex pattern has balanced brackets.
Predict Output
advanced
2: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)
A[[1]] "one" "two" "three"
B[[1]] "one1" "two22" "three333"
C[[1]] "1" "2" "3"
D[[1]] "1" "22" "333"
Attempts:
2 left
💡 Hint
gregexpr finds all matches of one or more digits, regmatches extracts them.
🧠 Conceptual
expert
2: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]])
A2
B3
C4
D1
Attempts:
2 left
💡 Hint
Lookahead '(?=a)' matches 'a' only if followed by another 'a'.