简体   繁体   中英

How to extract a substring from a string in python between a marker and the nth occurrence of another marker

Here's the string:

IP = "http://username:password@192.168.0.66/mjpg/video.mjpg"

I'd like to extract the IP address between @ and the third / to pass it as an argument to a function. That's one line among hundreds in a text file which I must loop through extracting only the IP addresses.

The following code doesn't work, and I don't know why. If I replace the / with /mjpg and remove the (3) it will work, but the video stream after the / isn't always mjpg and could be one of hundreds in the script I'm working on. Point is extracting the substring between the "@" and the third "/".

print(IP[IP.find("@")+1:IP.find(("/"),3)])

Can some spot the error or suggest a better approach?

Instead of finding the third occurrence of / , you can instead get the first occurrence of / after @

>>> start = IP.find("@")
>>> end   = IP.find("/", start)
>>> IP[start+1:end]
'192.168.0.66'

That being said, it is easier to use re.findall to do this

>>> import re
>>> re.findall(r'http:.*?//[^@]*@([0-9.]+)/', IP)
['192.168.0.66']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM