分析插入表达式外的字符串

2024-05-19 07:42:52 发布

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

我有以下文字:

s1 = 'Promo Tier 77 (4.89 USD)'
s2 = 'Promo (11.50 USD) Tier 1 Titles Only'

从这里,我想把括号里没有的数字取出来。它将是:

s1 --> '77'
s2 --> '1'

我目前正在使用弱正则表达式re.findall('\s\d+\s',s1)。什么是正确的正则表达式?类似于re.findall('\d+',s1)但不包括插入语中的任何内容。你知道吗

>>> re.findall('\d+',s1)
['77', '4', '89'] # two of these numbers are within the parenthetical. 
                  # I only want '77'

Tags: ofre内容only数字括号tierusd
3条回答

可以创建一个删除了括号部分的临时字符串,然后运行代码。我使用了一个空格,这样丢失的字符串部分前后的数字就不能连接起来了。你知道吗

>>> import re
>>> s = 'Promo Tier 77 (11.50 USD) Tier 1 Titles Only'
>>> temp = re.sub(r'\(.*?\)', ' ', s)
Promo Tier 77   Tier 1 Titles Only
>>> re.findall('\d+', temp)
['77', '1']

你当然可以把它缩短成一行。你知道吗

我发现有用的一种方法是,在上下文中使用alternation操作符,将要排除的内容放在左侧,(扔掉这个,这是垃圾),并将要匹配的内容放在右侧的捕获组中。你知道吗

然后可以将其与^{}结合使用,或者使用列表理解来删除正则表达式引擎从alternation操作符左侧的表达式中提取的空列表项。你知道吗

>>> import re
>>> s = """Promo (11.50 USD) Tier 1 Titles Only
Promo (11.50 USD) (10.50 USD, 11.50 USD) Tier 5
Promo Tier 77 (4.89 USD)"""
>>> filter(None, re.findall(r'\([^)]*\)|(\d+)', s))
['1', '5', '77']

把你的琴弦劈开。eg伪码

s1 = "Promo Tier 77 (4.89 USD)"
s  = s1.split(")")
for ss in s :
  if "(" in ss: # check for the open brace
     if the number in ss.split("(")[0]:  # split at the open brace and do your regex
        print the number

相关问题 更多 >

    热门问题