Python Regular Expressions in Python Introduction to Regular Expressions Escapes

Gabriel Alcaraz
Gabriel Alcaraz
3,335 Points

Didn't get the right match back. Got "1".

I try to get the match object but I don't know what that means, help?

escapes.py
import re

def first_number(x):
    x = '1234'
    num = re.match(r'\d', x)
    return num

2 Answers

Peter Vann
Peter Vann
26,484 Points

This passes:

import re

def first_number(x):
  return re.search(r'\d', x)
Gabriel Alcaraz
Gabriel Alcaraz
3,335 Points

ah i see what I did wrong thanks

Peter Vann
Peter Vann
26,484 Points

I kinda wish the challenges also let the student, not just write the function, but also use it in the code. For example:

import re

def first_number(x):
  return re.search(r'\d', x)

str_num = 'abc1234'

print( first_number(str_num)[0] )

(run with python3)

I think it would help the student better understand the syntax and how it really works.

BTW, I test simple python code snippets here: https://www.katacoda.com/courses/python/playground (If you run that code there it prints 1)

Also, I used this line of code:

print( first_number(str_num)[0] )

and not

print( first_number(str_num) )

because

print( first_number(str_num) )

prints <_sre.SRE_Match object; span=(3, 4), match='1'>

Anyway, glad I could help!