user3920295
user3920295

Reputation: 909

python - to extract a specific string

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!

Upvotes: 1

Views: 59

Answers (4)

arunkumar
arunkumar

Reputation: 34043

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.

Upvotes: 1

OneCricketeer
OneCricketeer

Reputation: 191681

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'

Regex Demo

Alternative regex

re.findall("index: ([^\s)]+)", s)[1]

Upvotes: 2

OrderAndChaos
OrderAndChaos

Reputation: 3850

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

Upvotes: 1

joel goldstick
joel goldstick

Reputation: 4483

>>> 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

Upvotes: 1

Related Questions