I have a string like :
string="(tag, index: develop-AB123-2s), (index: develop-CD123-2s)"
I want to extract only "develop-CD123-2s", i.e. the string that comes after "(index:" and not the one with tag. How do I do in python? Thanks!
4 Answers 4
Warning: I'm not the best at regex
import re
s='(tag, index: develop-AB123-2s), (index: develop-CD123-2s)'
print re.findall("\\(.*?index: ([^)]+)", s)[1] # 'develop-CD123-2s'
Alternative regex
re.findall("index: ([^\s)]+)", s)[1]
2 Comments
r"..." style strings with regex to avoid needing to use double slashes.(.*?, really.>>> string.split("), (")[1].split(":")[1].split(")")[0].strip()
'develop-CD123-2s'
>>>
The first split separates each tuple, then split on : and take the second result
Comments
You could do it like this:
string = "(tag, index: develop-AB123-2s), (index: develop-CD123-2s)"
string = string.split('(index:')
string = string[1].strip(')')
print(string)
split the string on (index: and strip off the closing curly bracket
Comments
One way is using python regex - positive lookbehind assertion
import re
string = "(tag, index: develop-AB123-2s), (index: develop-CD123-2s)"
re.findall(r"(?<=\(index:) ([^)]+)", string)
This pattern only matches things that start with (index:. You can also look at negative lookbehind assertions to try and match the (tag, part.