Python正则表达式拆分最后一个美元值

2024-10-02 12:27:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试使用python编写一个regex脚本,并重新打包最后一个美元值从字符串中分离出来。你知道吗

到目前为止,我的情况是:

import re
str = ['2 Apple pie $1.50 /each: $3.00',
   'Corsair Vengeance 8GB DDR3 1600 MHz (PC3 12800) Desktop Memory $34.99']

[re.split("([$]\d+\.\d{2}?)",i) for i in str] 

输出:

[['2 Apple pie ', '$1.50', ' /each: ', '$3.00', ''],
 ['Corsair Vengeance 8GB DDR3 1600 MHz (PC3 12800) Desktop Memory ','$34.99','']]

所需输出:

[['2 Apple pie $1.50 /each: ', '$3.00'],
 ['Corsair Vengeance 8GB DDR3 1600 MHz (PC3 12800) Desktop Memory ','$34.99']]

任何指示都会有帮助。提前谢谢!你知道吗


Tags: 字符串re脚本appleregexeachmemorydesktop
2条回答

我可以用你的例子来说明这一点:

import re
str = ['2 Apple pie $1.50 /each: $3.00',
   'Corsair Vengeance 8GB DDR3 1600 MHz (PC3 12800) Desktop Memory $34.99']

output = [re.match(r"(.+)(\$.*)$", x).groups() for x in str]
print output
# [('2 Apple pie $1.50 /each: ', '$3.00'), ('Corsair Vengeance 8GB DDR3 1600 MHz (PC3 12800) Desktop Memory ', '$34.99')]

regex利用了regex是贪婪的这一事实,因此通过让它在寻找后面有一些字符的$之前尽可能多地吞噬字符,我们可以隐式地告诉regex引擎在最后一个$上拆分。你知道吗

不能使用零宽度匹配的re模块进行拆分,但是可以将此模式(?=[$][0-9.]+$)regex module一起使用:

[regex.split("(?V1)(?=[$][0-9.]+$)", i) for i in str]

但是,可以使用美元符号前的空格使其与re模块一起工作:

[re.split(" (?=[$][0-9.]+$)",i) for i in str] 

相关问题 更多 >

    热门问题