0

I have a url that contains "#/mail_detail?mail_id=16e7e90049d734ed&_k=iddh5c" and from it I would like to store the value of mail_id till &.

Is there a simple way to do it using python?

Abhyudai
  • 826
  • 7
  • 16
  • There are many possibilities. You can use the URL parser module, or you can pull it out of the `str` yourself using the `re` module or simply work with strings. In my opinion, it is faster to work with `str` than module `re`. The `re` module is better for complicated operations with long text. Here you will find the answer for working with the `re` module or working with the `str`: https://stackoverflow.com/questions/32680030/match-text-between-two-strings-with-regular-expression and here you will find the manual for `urllib.parse` module: https://docs.python.org/3/library/urllib.parse.html – s3n0 Nov 18 '19 at 13:12

2 Answers2

0

You may use regular expressions (re library) to find all characters in between the string mail_id and the & character

import re
url = '#/mail_detail?mail_id=16e7e90049d734ed&_k=iddh5c'
print(re.findall(r'mail_id=(.*&)', url))

.* matches any no. of characters except a .

Abhyudai
  • 826
  • 7
  • 16
0

You can use re library to do the extraction easily. Assuming your url data type is a string here is the simple code to do so:

import re
url = "#/mail_detail?mail_id=16e7e90049d734ed&_k=iddh5c"
result = re.search("mail_id=(.*)&_k", url)
print(result.group(1))

Please note that using the command:

result = re.search("_id=(.*)&_k", url)

will yield the same result as well, but in case your string contains more than one such instances where "_id" appears, then it can be an ambiguous situation, where the output may be different. To ensure the 100 percent correct results, you should preferably include the more certain string keywords, around which you want to extract the text.

Shivam Sahil
  • 4,055
  • 3
  • 31
  • 62