Skip to main content
 首页 » 编程设计

python 正则表达式重新编译匹配

2025年05月04日20dudu

我正在尝试匹配(在 python 中使用正则表达式):

http://images.mymaterials.com/images/steel-images/small/steel/steel800/steel800-2.jpg 

在以下字符串中:

http://www.mymaterialssite.com','http://images.mymaterials.com/images/steel-images/small/steel/steel800/steel800-2.jpg','Model Photo' 

我的代码是这样的:

temp="http://www.mymaterialssite.com','http://images.mymaterials.com/images/steel-images/small/steel/steel800/steel800-2.jpg','Model Photo'" 
dummy=str(re.compile(r'.com'',,''(.*?)'',,''Model Photo').search(str(temp)).group(1)) 

我不认为“虚拟”是正确的,我不确定我是如何“转义”regex re.compile 命令中的单引号和双引号的。

我尝试用谷歌搜索这个问题,但找不到任何相关内容。

在此方面提供任何指导,我们将不胜感激。

谢谢。

请您参考如下方法:

在 Python 中处理包含转义字符和引号的字符串的最简单方法是用三重双引号将字符串 (""") 加上前缀 r . 例如:

my_str = r"""This string would "really "suck"" to write if I didn't 
 know how to tell Python to parse it as "raw" text with the 'r' character and 
 triple " quotes. Especially since I want \n to show up as a backlash followed 
 by n. I don't want \0 to be the null byte either!""" 

r 表示“将转义字符作为文字”。三重双引号 (""") 防止单引号、双引号和双引号过早结束字符串。

编辑:我将示例扩展为包括\0 和\n 之类的内容。在普通字符串(不是原始字符串)中,\(转义字符)表示下一个字符具有特殊含义。例如 \n 表示“换行符”。如果您确实想要字符 \ 后跟 n 在您的字符串中,您必须编写 \\n,或者只使用原始字符串,如我在上面的示例中所示。

您还可以在此处阅读 Python 文档中的字符串文字: