BubbleTea
BubbleTea

Reputation: 219

Adding a variable inside regex re.search() patern

I am trying to add a variable inside the regex patern for re.search() such as:

xvar=100
answer= re.search(r'(<a href=")(.+count=xvar.+?)(")', subreddit).group(2)

but i receive the error:

    nexturl = re.search(r'(<a href=")(.+count=xvar.+?)(")', subreddit).group(2) AttributeError: 'NoneType' object has no attribute 'group'

How do i fix this to do what i want it to do?

Upvotes: 0

Views: 80

Answers (5)

hostingutilities.com
hostingutilities.com

Reputation: 9519

xvar=100
answer= re.search('(<a href=")(.+count=' + str(xvar) + '.*?)(")', subreddit).group(2)

or

xvar=100
answer= re.search('(<a href=")(.+count=%s.*?)(")' % xvar, subreddit).group(2)

or

xvar=100
answer= re.search('(<a href=")(.+count={0}.*?)(")'.format(xvar), subreddit).group(2)

See https://mkaz.com/2012/10/10/python-string-format/ for more info on formatted strings

Upvotes: 2

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626870

Beside the variable issue (you should convert an xvar int to string using str()), I think the problem is also in using .+?. If you replace it with .*? you will get a match, and group(2) will be accessible.

Try this code:

import re

xvar=100
subreddit = r'<a href="something" count="100">Text</a>'
answer= re.search( r'(<a href=")(.+count="' + str(xvar) + r'.*?)(")', subreddit).group(2)

Output:

something" count="100

Here is a sample demo program in Python.

Upvotes: 1

a p
a p

Reputation: 3208

Generally, there are 3 ways to do this (it's called formatting or interpolation, generally):

some_string = "dogs are cute :)"
# very basic, using concatenation: 
print "All " + some_string + " and go to heaven."
# Or, using the interpolate operator: 
print "All %s and go to heaven."    # Use %d for digits, %f for floats, %s for strings, etc. You have to be specific with the variable type. 
# Or use string format: 
print "All {} and go to heaven.".format(some_string)

Format is considered the 'best' practice in most scenarios, though you'll see the interpolate % around a lot. Check out the full format syntax at https://docs.python.org/2/library/stdtypes.html#string-formatting

Upvotes: 0

Malik Brahimi
Malik Brahimi

Reputation: 16711

Use string formatting:

r'(<a href=")(.+count={}.+?)(")'.format(xvar)

Upvotes: 1

Kasravnd
Kasravnd

Reputation: 107287

You can use format, and for handle the exception use a try-except :

xvar=100
try:
    answer= re.search(r'(<a href=")(.+count={}.+?)(")'.format(xvar), subreddit).group(2)
except AttributeError:
    print 'no match'

Upvotes: 1

Related Questions