0
<script>
    function foo() {
        var bar = 'thisisvalue';
    }   
</script>

Hi all, I have this function in script tag and I want to get the value of var bar by using Python regular expression. Can anyone help me with this. Thanks

3
  • Are you sure the text var bar = won't appear elsewhere in the page? Commented Aug 24, 2018 at 23:58
  • assume var bar = is unique Commented Aug 24, 2018 at 23:59
  • 1
    Current code/approach ..? There are multiple steps, "get html as string", "apply regex to extract value", etc. Questions should generally provide code so that a single step can be focused on and explained in context what the current context. Both of the steps isolated above are already covered in countless tutorials. Commented Aug 25, 2018 at 0:00

2 Answers 2

1

The pattern I always use in python is this:

import re
SEARCHER = re.compile( *regex with captured groups* )

...later, in a loop over lines...

  search = SEARCHER.search(line)
  if search:
     value = search.group(1)

In your particular case it would be something like this:

import re
VARBAR_SEARCHER = re.compile(r"var bar = '([^']*)'")

...

  search = VARBAR_SEARCHER.search(line)
  if search:
     value = search.group(1)

This omits the single quotes from the value. If you wanted those in there you could modify the regular expression.

Sign up to request clarification or add additional context in comments.

Comments

0
for line in html:
     if 'var bar =' in line:
         thisisvalue = line.split("'")[1]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.