在regex re.search()patern中添加一个变量



我正试图在regex patern中添加一个变量,用于re.search(),例如:

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

但我收到错误:

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

我该如何修复它以实现我希望它做的事情?

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

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

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

请参阅https://mkaz.com/2012/10/10/python-string-format/有关格式化字符串的更多信息,

您可以使用format,并且使用try-except:来处理异常

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

使用字符串格式:

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

除了变量问题(应该使用str()xvar int转换为string)之外,我认为问题还在于使用.+?。如果您将其替换为.*?,您将获得一个匹配项,并且group(2)将可以访问。

试试这个代码:

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)

输出:

something" count="100

下面是一个Python的示例演示程序。

通常有三种方法可以做到这一点(通常称为格式化或插值):

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)

在大多数情况下,格式被认为是"最佳"实践,尽管你会看到很多插值%。查看完整格式语法https://docs.python.org/2/library/stdtypes.html#string-格式化

最新更新