0

I have a string and I want to extract a substring from that main string

Some sample strings are:

http://domain.com/xxxxx/xxxxxxxx?tags=%7C105651%7C102496&Asidebar=1&dnr=y
http://domain.com/xxxxx/xxxxxx?tags=%7C12784%7C102496&index=28&showFromBeginning=true&

I want to get the tags value.

In this case:

val = %7C105651%7C102496

val = %7C12784%7C102496

Is there any chance to get that?

Edit

tags = re.search('tags=(.+?)&Asidebar', url)
print tags
if tags:
    found = tags.group(1)
    print (found)
output: None

Note: I've just tried to get something from the first string only

2
  • 1
    There is a great chance. Can you show us what you came up with so far? Commented Nov 25, 2014 at 13:46
  • sure, wait, I'm editing it Commented Nov 25, 2014 at 13:47

2 Answers 2

3

Using urlparse.urlparse and cgi.parse_qs (Python 2.x):

>>> import urlparse
>>> import cgi
>>>
>>> s = 'http://domain.com/xxxxx/xxxxxxxx?tags=%7C105651%7C102496&Asidebar=1&dnr=y'
>>> cgi.parse_qs(urlparse.urlparse(s).query)
{'dnr': ['y'], 'Asidebar': ['1'], 'tags': ['|105651|102496']}
>>> cgi.parse_qs(urlparse.urlparse(s).query)['tags'][0]
'|105651|102496'

In Python 3.x, use urllib.parse.urlparse and urllib.parse.parse_qs:

>>> import urllib.parse
>>>
>>> s = 'http://domain.com/xxxxx/xxxxxxxx?tags=%7C105651%7C102496&Asidebar=1&dnr=y'
>>> urllib.parse.parse_qs(urllib.parse.urlparse(s).query)['tags'][0]
'|105651|102496'
Sign up to request clarification or add additional context in comments.

3 Comments

really thanks. but it seems it is pretty advance.. I'm new to PY and will stick to easyone Thanks for your effort
@MMK, Isn't this easy? The function will care edge case for you. Try http://domain.com/xxxxx/xxxxxxxx?tags=%7C105651%7C102496 / http://domain.com/xxxxx/xxxxxxxx?tags=
sure..I'm checking it.
3

You're almost there. You don't need to write Asidebar in your regex. Because in your second input string, there isn't a substring called Asidebar.

tags = re.search('tags=(.+?)&', url)
if tags:
    found = tags.group(1)
    print (found)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.