Regular Expressions — Concept Check
Questions on Regular Expressions. Java's java.util.regex package provides compiled patterns and matchers for searching, extracting, and replacing text with regular expressions.
Questions in this quiz
8 questions on Regular Expressions — Concept Check. Work through them here, then start the quiz to answer them and see your score.
1.You have a Java method using `String.matches()` to validate email addresses. Why might this be inefficient?
- A`matches()` compiles the pattern every call.
- B`matches()` only works for exact matches.
- C`matches()` is case-sensitive by default.
- D`matches()` cannot handle complex patterns.
2.A developer uses `Pattern.CASE_INSENSITIVE` but finds 'Hello' does not match 'HELLO'. Why?
- AThe flag was not applied correctly.
- BThe input string is too short.
- CCASE_INSENSITIVE only affects letters.
- DThe pattern syntax is incorrect.
3.Given the regex `\d{4}-\d{2}-\d{2}`, what does `group(1)` return when matching '2025-06-15'?
- A'2025'
- B'15'
- CNothing, it's not captured.
- D'06'
4.Why is it beneficial to use `Pattern.compile()` for regex patterns used multiple times?
- AIt avoids recompiling the pattern on each use.
- BIt ensures the pattern is always correct.
- CIt automatically optimizes the regex.
- DIt makes the code more readable.
5.A regex with `(?m)` flag doesn't match expected line starts/ends. What's likely wrong?
- AThe pattern syntax is incorrect.
- BThe MULTILINE flag is not set correctly.
- CThe input string is too short.
- DThe input string lacks line breaks.
6.You use `replaceAll()` to mask digits but find it slow. What's a better approach?
- AUse a simple loop instead of regex.
- BCompile the pattern once and reuse it.
- CUse `replaceFirst()` instead.
- DSwitch to `replace()` method.
7.When using `Pattern.MULTILINE`, what does `^` match?
- AThe end of each line.
- BThe end of the entire input.
- CThe start of each line.
- DThe start of the entire input.
8.What happens if you use `(?i)` in a regex pattern?
- AThe pattern matches any character.
- BThe pattern becomes case-insensitive.
- CWhitespace in the pattern is ignored.
- DThe pattern matches line boundaries.