⊗pyPmREMSe 51 of 128 menu

The search method in Python regular expressions

In previous lessons we have studied regular expressions using the search and replace method. There are other methods as well. In this lesson we will start to study them.

The new method we'll be learning is called search. It looks for the first match with a regular expression in a string. The first parameter of the method requires the regular expression to be searched for, and the second parameter specifies the string in which to search for it. The method checks for matches by going through the string from left to right.

The method returns a special match object, containing information about the found substring and its location in the original string.

Let's try it in practice. Let's find the first substring with numbers using the search method:

txt = 'aaa 123 bbb 456' res = re.search('\d+', txt)

Let's find the first substring with numbers using the search method:

print(res) # there will be a match object

Now let's output the found text. It will fall into the zero element of the match object:

print(res[0]) # '123'

Given a string:

txt = '123 abc 456 cde'

Find the first substring that contains only alphabetic characters. Print it to the console.

Given a string:

txt = '1 23 456 789'

Find the position of the first three-digit number.

enru