re.match().groups() 是如何工作的?
我正在尝试使用 re.match().groups() 从一个字符串中提取一些信息:
s = "javascript:Add2ShopCart(document.OrderItemAddForm,%20'85575',%20'Mortein%20Mouse%20Trap%201%20pack',%20'',%20'$4.87');"
我想要的结果是:
("Mortein%20Mouse%20Trap%201%20pack", "4.87")
所以我一直在尝试:
re.match(r"(SEPARATOR)(SEPARATOR)", s).groups() #i.e.:
re.match(r"(\',%20\')(\$)", s).groups()
我试着查看了 re 的文档,但是因为我的正则表达式技能太差了,所以对我帮助不大。
更多的示例输入:
javascript:Add2ShopCart(document.OrderItemAddForm,%20'85575',%20'Mortein%20Mouse%20Trap%201%20pack',%20'',%20'$4.87');
javascript:Add2ShopCart(document.OrderItemAddForm_0,%20'85575',%20'Mortein%20Mouse%20Trap%201%20pack',%20'',%20'$4.87');
javascript:Add2ShopCart(document.OrderItemAddForm,%20'8234551',%20'Mortein%20Naturgard%20Fly%20Spray%20Eucalyptus%20320g',%20'',%20'$7.58');
javascript:Add2ShopCart(document.OrderItemAddForm,%20'4204369',%20'Mortein%20Naturgard%20Insect%20Killer%20Automatic%20Outdoor%20Refill%20152g',%20'',%20'$15.18');
javascript:Add2ShopCart(document.OrderItemAddForm_0,%20'4204369',%20'Mortein%20Naturgard%20Insect%20Killer%20Automatic%20Outdoor%20Refill%20152g',%20'',%20'$15.18');
javascript:Add2ShopCart(document.OrderItemAddForm,%20'4220523',%20'Mortein%20Naturgard%20Outdoor%20Automatic%20Prime%201%20pack',%20'',%20'$32.54');
3 个回答
0
这不是一个正则表达式的简单解决方案,希望这对你有帮助:
In [16]: s="""s = javascript:Add2ShopCart(document.OrderItemAddForm,%20'85575',%20'Mortein%20Mouse%20Trap%201%20pack',%20'',%20'$4.87');"""
In [17]: arr=s.split("',%20'")
In [18]: arr[1]
Out[18]: 'Mortein%20Mouse%20Trap%201%20pack'
In [19]: re.findall("(?<=\$)[^']*",arr[3])
Out[19]: ['4.87']
1
你可以使用
javascript:Add2ShopCart.*?,.*?,%20'(.*?)'.*?\$(\d+(?:\.\d+)?)
第1组和第2组捕获了你想要的内容。
2
re.findall(r"""
' #apostrophe before the string Mortein
( #start capture
Mortein.*? #the string Moretein plus everything until...
) #end capture
' #...another apostrophe
.* #zero or more characters
\$ #the literal dollar sign
( #start capture
.*? #zero or more characters until...
) #end capture
' #an apostrophe""", s, re.X)
这段代码会返回一个数组,里面包含了 Mortein
和 $
的金额,作为一个元组。你也可以使用:
re.search(r"'(Mortein.*?)'.*\$(.*?)'", s)
这段代码会返回一个匹配结果。.group(1)
是 Mortein
,而 .group(2)
是 $
。.group(0)
则是整个匹配到的字符串。