hulk007
hulk007

Reputation: 2971

Catching a selected text from the string in python

The variable Field stores a string like the following:

Field = "In Field 'Testing':(Value1) has changed from (1) to (2)"

I am looking for a way to extract the field name from that variable and store it a variable called name. In the example above, the field name is Testing.

Upvotes: 1

Views: 154

Answers (2)

Maroun
Maroun

Reputation: 95968

The regular expression you're looking for is:

'(.*?)'

In Python you can write:

>>> import re
>>> Field= "In Field 'Testing':(Value1) has changed from (1) to (2)"
>>> print re.findall("'(.*?)'", Field) #Will print Testing

After you get Testing, I'm sure you'll have no problem to print it like name=Testing


Edit

To print it as you wish, you can:

print ''.join(re.findall("'(.*?)'", Field))

Upvotes: 2

Ofiris
Ofiris

Reputation: 6151

If you don't want to use Regex:

Field.split('\'')[1]

Or another way,

first_index = Field.index('\'') //Search for first '
second_index = Field.index('\'', first_index+1) //Search for second '
Field[first_index+1:second_index] //"Testing" //Substring

Upvotes: 1

Related Questions