You want to write a regex literal in Ruby that matches strings starting with "cat" or "dog". Which regex literal achieves this?
hard📝 Application Q8 of 15
Ruby - Regular Expressions
You want to write a regex literal in Ruby that matches strings starting with "cat" or "dog". Which regex literal achieves this?
A/^(cat|dog)$/
B/cat|dog$/
C/cat|dog/
D/^(cat|dog)/
Step-by-Step Solution
Solution:
Step 1: Understand anchors and alternation
^ means start of string, $ means end. (cat|dog) means either 'cat' or 'dog'.
Step 2: Evaluate options
/^(cat|dog)/ matches strings starting with 'cat' or 'dog'. /cat|dog$/ matches 'cat' anywhere or 'dog' at end. /cat|dog/ matches 'cat' or 'dog' anywhere. /^(cat|dog)$/ matches exactly 'cat' or 'dog' only.
Final Answer:
/^(cat|dog)/ -> Option D
Quick Check:
Use ^ and (cat|dog) to match start with either word [OK]
Quick Trick:Use ^(cat|dog) to match start with 'cat' or 'dog' [OK]
Common Mistakes:
Misplacing anchors ^ and $
Not grouping alternatives with parentheses
Assuming | has higher precedence than anchors
Master "Regular Expressions" in Ruby
9 interactive learning modes - each teaches the same concept differently