Python Regex从字符串中提取代码

2024-09-28 03:21:03 发布

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

我有一根绳子像-

Srting = "$33.53 with 2 coupon codes : \r\n\r\n1)  CODEONE\r\n\r\n2)  
CODETWO \r\n\r\nBoth coupons only work if you buy 1 by 1"

如果下面的if条件为真,我想从这个字符串中提取优惠券代码“CODEONE”和“code2”—

if  "coupon code" in string:

请帮助我如何提取这些优惠券代码?实际上,我需要一个通用的RE,因为我可能有其他字符串,其中代码的位置可能出现在不同的地方,也可能只有一个代码


Tags: 字符串代码ifwithcodes优惠券couponn2
1条回答
网友
1楼 · 发布于 2024-09-28 03:21:03

这也许会有帮助。你知道吗

import re
Srting = "$33.53 with 2 coupon codes : \r\n\r\n1)  CODEONE\r\n\r\n2) CODETWO \r\n\r\nBoth coupons only work if you buy 1 by 1"

for i in re.findall("\d+\)(.*)", Srting):
    print(i.strip())

输出:

CODEONE
CODETWO

相关问题 更多 >

    热门问题