3

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 ?

dot.Py
  • 5,007
  • 5
  • 31
  • 52
yixian he
  • 57
  • 1
  • 6
  • 1
    This one was probably already answered here: http://stackoverflow.com/questions/11686516/python-regexp-global-flag – theWanderer4865 Mar 30 '17 at 14:50
  • 2
    `match` matches from the beginning of the string. See [search() vs match()](https://docs.python.org/3/library/re.html#search-vs-match). – khelwood Mar 30 '17 at 14:51
  • Alternatively you can get the `user id` by using `s.split('=')[1]` – dot.Py Mar 30 '17 at 14:52
  • Thanks, this solves my confusion. I'm trying to do regex instead of string manipulation since there is not much chance to practice them during work – yixian he Mar 30 '17 at 14:59

1 Answers1

2

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
Community
  • 1
  • 1
dot.Py
  • 5,007
  • 5
  • 31
  • 52