python regex re.compile匹配

时间:2012-02-29 21:46:22

标签: python regex

我正在尝试匹配(在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命令中的单引号和双引号。

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

对此有任何指导意见。

感谢。

4 个答案:

答案 0 :(得分:7)

在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文档中阅读有关字符串文字的内容:

答案 1 :(得分:0)

尝试三重引号:

import re
tmp=""".*http://images.mymaterials.com/images/steel-images/small/steel/steel800/steel800-2.jpg.*"""
str="""http://www.mymaterialssite.com\'\,\'http://images.mymaterials.com/images/steel-images/small/steel/steel800/steel800-2.jpg','Model Photo'"""
x=re.match(tmp,str)
if x!=None:
    print x.group()

你也错过了。*在模式的开头和结尾。我也补充说。

答案 2 :(得分:0)

逗号不需要转义,如果使用双引号创建字符串,则不需要转义单引号:

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

请注意,我还删除了一些不必要的str()调用,如果您确实需要转义单引号或双引号(比如您的字符串包含两者),请使用反斜杠:

'.com\',\'(.*?)\',\'Model Photo'

正如mykhal在评论中指出的那样,这与正则表达式不能很好地协作,因为你不能再使用原始字符串(r'...')字面值。更好的解决方案是使用三引号字符串作为其他答案。

答案 3 :(得分:0)

如果使用双引号(与Python中的单引号具有相同的含义),则根本不必转义..(在本例中)。你甚至可以在没有起始r的情况下使用字符串文字(你没有任何反斜杠)

re.compile(".com','(.*?)','Model Photo")