Explore the use of caret (^) and dollar sign ($) anchors in regular expressions, learn how they define string boundaries, and test your ability to recognize their correct and incorrect usage. This quiz is designed to reinforce key regex concepts for developers and data professionals.
Which of the following regular expressions will match the word 'cat' only if it appears at the very beginning of a line?
Explanation: The caret symbol (^) used at the beginning of a regex pattern, as in ^cat, matches 'cat' only at the start of a line. 'cat$' matches 'cat' at the end of a line, not the beginning. 'c^at' is not a valid anchor placement, and 'cat' alone matches 'cat' anywhere in the line, not just at the start.
If you apply the regular expression 'dog$' to the string 'My favorite pet is a dog', what will the outcome be?
Explanation: The dollar sign ($) in 'dog$' ensures that 'dog' is matched only if it is at the very end of the string. The regex will not match 'dog' if it appears elsewhere. The statement about every word ending with 'dog' is incorrect because the pattern anchors to the end of the entire string, not individual words. '$' is a valid anchor, so the option stating otherwise is not accurate.
What will the regular expression '^hello$' match in the string 'hello worldnhello'?
Explanation: The combined use of ^ and $ ensures the regex matches only if the entire line is exactly 'hello'. It will not match 'hello' as part of 'hello world' or any substring. The anchors operate on line boundaries, refuting the option claiming they only apply to characters. The pattern does not match every occurrence, just exact matches.
Given the string 'start middle end', what does the regular expression 'middle' (without anchors) match?
Explanation: When 'middle' is used without anchors, it will match the substring 'middle' wherever it appears in the text. The presence of anchors is necessary to restrict matches to the start or end of the string. Saying it does not match at all is incorrect, since the anchors are optional for matching substrings.
What is the significance of placing the caret (^) character inside square brackets, as in '[^aeiou]'?
Explanation: When the caret appears immediately after the opening bracket, it negates the character class, so '[^aeiou]' matches any character that is not a vowel. Matching the caret literally would require escaping or placement elsewhere. Anchoring to start or both ends is not the function of caret inside square brackets. The pattern operates as a negation, not an anchor.