yixian he
yixian he

Reputation: 57

How can I use re.match to find numbers?

I'm trying to use python re module:

import re

res = re.match(r"\d+", 'editUserProfile!input.jspa?userId=2089')
print(res)

I got None type for res, but if I replace the match by findall, I can find the 2089.

Do you know where the problem is ?

Upvotes: 3

Views: 4269

Answers (1)

dot.Py
dot.Py

Reputation: 5157

The problem is that you're using match() to search for a substring in a string.

The method match() only works for the whole string. If you want to search for a substring inside a string, you should use search().

As stated by khelwood in the comments, you should take a look at: Search vs Match.


Code:

import re
res = re.search(r"\d+", 'editUserProfile!input.jspa?userId=2089')
print(res.group(0))

Output:

2089

Alternatively you can use .split() to isolate the user id.

Code:

s = 'editUserProfile!input.jspa?userId=2089'
print(s.split('=')[1])

Output:

2089

Upvotes: 3

Related Questions