如何在Python中使用变量进行正则表达式搜索?

时间:2015-12-03 18:42:46

标签: python xbmc kodi

有没有人能告诉我如何在Python中使用变量url进行正则表达式搜索?Url是传递给保存下面代码的函数的变量。我尝试了以下但继续得到错误。希望有人帮我解决这个错误。谢谢提前。 示例str和url值:

str='.......href="http://somewebsite:8080/hls/1.m3u8?session=34534525".....'
url='http://somewebsite:8080/hls/1.m3u8?session='

python代码:

foundValue= re.search('+url+(.*)"', str)
print 'foundValue:'
print foundValue.group(1);
xbmc日志上的

错误:

ERROR: EXCEPTION Thrown (PythonToCppException) :
 -->Python callback/script returned the following error<--
- NOTE: IGNORING THIS CAN LEAD TO MEMORY LEAKS!
Error Type: <class 'sre_constants.error'>
Error Contents: nothing to repeat
Traceback (most recent call last):
File "F:\......\addon.py", line 281, in <module>
play_video(url)
File "F:\.......\addon.py", line 160, in play_video
foundValue = re.search('+url+(.*)"', str)
File "F:\.....\XBMC\system\python\Lib\re.py", line 142, in search
return _compile(pattern, flags).search(string)
File "F:\....\XBMC\system\python\Lib\re.py", line 242, in _compile
raise error, v # invalid expression
error: nothing to repeat
-->End of Python script error report<--

2 个答案:

答案 0 :(得分:2)

foundValue= re.search(re.escape(url)+r'(.*?)"', str1)

猜猜你想要这个。也不要使用内置的str

答案 1 :(得分:0)

另一个选择是使用format来创建字符串:

found_value = re.search(r'{0}(.*)"'.format(url), search_string)

请注意,Python中变量名称的标准是words_separated_by_underscores(请参阅PEP 008),并且提到@vks时,请避免使用str作为变量,因为它会影响内置str类。