Explore the fundamentals of regular expression character classes and ranges with targeted, scenario-based questions. Strengthen your understanding of regex syntax and improve your ability to build flexible patterns for string matching tasks.
Which regex pattern matches any single lowercase letter from 'a' to 'z' in the word 'apple'?
Explanation: [a-z] defines a character class that matches any single lowercase letter between a and z, which applies to the word 'apple'. [A-Z] is incorrect because it matches only uppercase letters. (a-z) is not a valid regex syntax and would not function as a character class. {a-z} is also incorrect since curly brackets are used for quantifiers, not character classes.
What does the regex pattern [^0-9] match in the string 'Room42'?
Explanation: [^0-9] defines a negated character class and matches any character that is not a digit, so it would match 'R', 'o', 'o', and 'm' in 'Room42'. [0-9] would match only digits, making that option incorrect. A dash or a caret is not relevant here since they are used as special characters in regex patterns. Only alphabetic letters is too restrictive because the character class could also match symbols or spaces.
Which character class matches any uppercase or lowercase English letter in the pattern?
Explanation: [A-Za-z] combines both uppercase and lowercase letter ranges, ensuring a match with any English letter. [a-zA-Z0-9] includes digits, so it is broader than needed. [a-z] only matches lowercase letters, and [A-Z0-9] matches only uppercase letters and digits, which makes both options incomplete for this scenario.
In regex, what does the character class [dw] match?
Explanation: [dw] matches either any digit (d) or any word character (w), where word characters include letters, digits, and underscores. Only whitespace characters are matched by the s class, so that option is incorrect. Any non-digit character would require a caret, such as [^d]. Matching only letters, not digits, would exclude digits, but w includes digits by definition.
How does the regex pattern [a-z-] differ from [a-z]?
Explanation: [a-z-] includes the range a to z and specifically adds the hyphen as a literal match, so it matches lowercase letters or hyphen characters. [a-z] excludes the hyphen, so option two is incorrect. Matching only the hyphen is wrong, as the range includes all lowercase letters as well. Option four is incorrect because the hyphen, when placed at the end or start inside the brackets, is considered a literal character.