0

First time working with Python Regex and I just need a little tip on matching strings.

I have a url like this: url = "https://www.youtube.com/api/timedtext?xorp=True&xoaf=1&v=UloIw7dhnlQ&signature=C2AF3C2887A37043353A86AAAACFA796659B56CB.E736B7146447843F2D3311234744DC0D9937AF7B&asr_langs=fr%2Cru%2Ces%2Cnl%2Cit%2Cde%2Cko%2Cen%2Cpt%2Cja&sparams=asr_langs%2Ccaps%2Cv%2Cxoaf%2Cxorp%2Cexpire&expire=1541769991&key=yttt1hl=&encaps=asrlang=enfmt=srv3"

I am trying to match everything except the part that begins with expire=1541769991 (2nd to last line). This is what I have come up with:

matchObj = re.match( r'(.*)expire=(.*)&(.*?)', url)

The problem is the third group includes the text after the last occurrence of &. I want the text following the first occurrence of & after expire=. I tried adding a ? after & to make it non-greedy too. How would I go about doing this?

2 Answers 2

2

Try this regex,

matchObj = re.match( r"(.*)expire=[^&]*(&.*)", url)
Sign up to request clarification or add additional context in comments.

Comments

1

You could do something like this:

import re

url = "https://www.youtube.com/api/timedtext?xorp=True&xoaf=1&v=UloIw7dhnlQ&signature=C2AF3C2887A37043353A86AAAACFA796659B56CB.E736B7146447843F2D3311234744DC0D9937AF7B&asr_langs=fr%2Cru%2Ces%2Cnl%2Cit%2Cde%2Cko%2Cen%2Cpt%2Cja&sparams=asr_langs%2Ccaps%2Cv%2Cxoaf%2Cxorp%2Cexpire&expire=1541769991&key=yttt1hl=&encaps=asrlang=enfmt=srv3"

match = re.match("(.+?)(expire=.+?&)(.+$)", url)
print(match.group(1) + match.group(3))

Output

https://www.youtube.com/api/timedtext?xorp=True&xoaf=1&v=UloIw7dhnlQ&signature=C2AF3C2887A37043353A86AAAACFA796659B56CB.E736B7146447843F2D3311234744DC0D9937AF7B&asr_langs=fr%2Cru%2Ces%2Cnl%2Cit%2Cde%2Cko%2Cen%2Cpt%2Cja&sparams=asr_langs%2Ccaps%2Cv%2Cxoaf%2Cxorp%2Cexpire&key=yttt1hl=&encaps=asrlang=enfmt=srv3

Or if you simply want the text without the expire=, you can remove it:

result = re.sub("expire=\d+?&", "", url)

Note that assumes that the value of expire are all digits.

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.