MalTec
MalTec

Reputation: 1370

Python RegEx Search for finding variable value from a string

I have a HTML string coming from server. I would like to fetch right side of the token.

vega.csrfToken = "019387r218r72r696r826r87469786487";

I am using .*csrfToken[\s="\w]+ to match entire line with

csrfToken =  re.search('.*csrfToken[\s="\w]+', text, re.MULTILINE)

Whereas certain regex tester portal works, Python fails to find the line. What are the changes required to match the line? What would be the best way to get only the RHS to = in the line.

Upvotes: 0

Views: 1085

Answers (1)

Kasravnd
Kasravnd

Reputation: 107287

First of all you need to use a r prefix for your regex because it needs to get interpreted as a raw string. Secondly the part [\s="\w]+ will match any combination of whitespace, equal sign, double quote and word character with length 1 or more which wont give you the exact part your want. Also you need to use capture grouping in order to get the expected part.

So you can simply use following regex:

csrfToken =  re.search(r'.*csrfToken\s=\s"(\w+)"', text, re.MULTILINE)

And get the expected part using csrfToken.group(1)

Upvotes: 1

Related Questions