简体   繁体   中英

how to use variable inside Python a regular expression search?

could any one show me how i can use variable url inside Python a regular expression search?Url is the variable passed to the function that holds the code below. I tried the following but keep getting error.Hope some help me fix this error.Thanks in advance. sample str and url value:

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

python code:

foundValue= re.search('+url+(.*)"', str)
print 'foundValue:'
print foundValue.group(1);

error on xbmc logs:

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

Another option is to use format to make the string:

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

Note that the standard for variable names in Python is words_separated_by_underscores (see PEP 008 ), and as @vks mentioned, avoid use of str as a variable as it shadows the builtin str class.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM