RowenaRavenclaw RowenaRavenclaw - 1 year ago 39
Python Question

grep a string after pattern match in python

I want to extract the testbed name from a file. This is the line where the name is present, How could I do it in Python?

Status: aaa (image='some_image_name' on testbed='test_bed_name' archiving)

I was thinking of splitting the string taking the index, but this line may not be the same in all my files. there might be some small changes.


If the format is always like that, you could simply slice your way to the right place:

>>> s.split('=')[-1].split(' ')[0][1:-1]

Or, you can use regular expressions:

>>> re.findall(r"(?:.*?)testbed='(.*?)'(?:.*?)", s)

The above is a bit of a ham-fisted approach to regular expressions, but you can always tweak it out to make it a bit more precise.