【问题标题】:how to use variable inside Python a regular expression search?如何在 Python 中使用变量进行正则表达式搜索?
【发布时间】:2015-12-03 18:42:45
【问题描述】:

谁能告诉我如何在 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<--

【问题讨论】:

    标签: python xbmc kodi


    【解决方案1】:

    猜你想要这个:

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

    也不要使用str,因为它是内置的。

    【讨论】:

      【解决方案2】:

      另一种选择是使用格式来制作字符串:

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-12-09
        • 2014-10-21
        相关资源
        最近更新 更多