簡體   English   中英

如何在Python中使用變量進行正則表達式搜索?

[英]how to use variable inside Python a regular expression search?

有人能告訴我如何在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<--
foundValue= re.search(re.escape(url)+r'(.*?)"', str1)

猜猜你想要這個,也不要內置使用str

另一種選擇是使用格式來生成字符串:

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

請注意,Python中變量名的標准是words_separated_by_underscores(請參閱PEP 008 ),並且正如@vks所述,請避免將str用作變量,因為它會遮蓋內置的str類。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM