Bird
0
0

How can you use the match method to check if a string contains only digits and extract them?

hard📝 Application Q9 of 15
Ruby - Regular Expressions
How can you use the match method to check if a string contains only digits and extract them?
Am = str.match(/^\d+$/); digits = m[0] if m
Bm = str.match(/\d+/); digits = m[1]
Cm = str.match(/\D+/); digits = m[0]
Dm = str.match(/\d+/); digits = m[0] unless m.nil?
Step-by-Step Solution
Solution:
  1. Step 1: Use regex to match entire string of digits

    The regex /^\d+$/ ensures the whole string contains only digits.
  2. Step 2: Extract matched digits safely

    If m is not nil, m[0] contains the digits.
  3. Final Answer:

    m = str.match(/^\d+$/); digits = m[0] if m -> Option A
  4. Quick Check:

    Use anchors ^$ to match whole string digits = B [OK]
Quick Trick: Use ^ and $ anchors to match entire string [OK]
Common Mistakes:
  • Using partial match regex
  • Accessing wrong group index
  • Not checking for nil

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes