Skip to main content
 首页 » 编程设计

python之如何使用正则表达式从这样的字符串中提取两个值

2025年05月04日21jirigala

如何使用一个正则表达式从以下字符串中获取值?

/*##debug_string:value/##*/ 

或

/*##debug_string:1234/##*/ 

或

/*##debug_string:http://stackoverflow.com//##*/ 

结果应该是

value 
1234 
http://stackoverflow.com/ 

请您参考如下方法:

试图阅读你的模式背后

re.findall("/\*##debug_string:(.*?)/##\*/", your_string) 

请注意,您的变体无法工作,因为您没有转义 *。在正则表达式中,* 表示重复前一个字符/组。如果您真的是指 * 字符,则必须使用 \*。

import re 
print re.findall("/\*##debug_string:(.*?)/##\*/", "/*##debug_string:value/##*/") 
print re.findall("/\*##debug_string:(.*?)/##\*/", "/*##debug_string:1234/##*/") 
print re.findall("/\*##debug_string:(.*?)/##\*/", "/*##debug_string:http://stackoverflow.com//##*/") 

执行为:

['value'] 
['1234'] 
['http://stackoverflow.com/'] 

编辑: 好的,我知道您可以有一个 URL。我已经修改了模式以将其考虑在内。