Loïc
Loïc

Reputation: 11943

How to return just a specific part of the regex?

import re

url = 'http://xxxxx.com/detail/028QCQZ?things_here'
re.search("detail/([A-Z0-9]+)\?", url).group()

returns :

'detail/028QCQZ?'

I thought that parenthesis were used in regular expressions to specify which part of the string to return.

I'd like to get only the code : 028QCQZ

Upvotes: 2

Views: 164

Answers (1)

anubhava
anubhava

Reputation: 784958

You need to use 1st captured group like this:

re.search("detail/([A-Z0-9]+)\?", url).group(1)
//=> 028QCQZ

If you use lookarounds then you can use group() like this:

re.search(r"(?<=detail/)[A-Z0-9]+(?=\?)", url).group()
//=> 028QCQZ

Upvotes: 3

Related Questions