【发布时间】:2019-03-26 17:26:07
【问题描述】:
不确定这是否应该是赏金。我只是想更好地理解正则表达式。
我查看了 Regex to match pattern.one skip newlines and characters until pattern.two 和 Regex to match if given text is not found and match as little as possible 线程中的回复,并在 RexEgg 上阅读了有关 Tempered Greedy Token Solutions 和 Explicit Greedy Alternation Solutions 的信息,但诚然,这些解释让我感到困惑。
最后一天我主要是在摆弄 re.sub(和 findall),因为 re.sub 的行为对我来说很奇怪。
.
问题 1:
给定下面带有字符后跟/ 的字符串,我将如何生成一个使用交替捕获组的单一正则表达式(仅使用re.sub 或re.findall),该捕获组必须使用[\S]+/ 才能获得所需的输出
>>> string_1 = 'variety.com/2017/biz/news/tax-march-donald-trump-protest-1202031487/'
>>> string_2 = 'variety.com/2017/biz/the/life/of/madam/green/news/tax-march-donald-trump-protest-1202031487/'
>>> string_3 = 'variety.com/2017/biz/the/life/of/news/tax-march-donald-trump-protest-1202031487/the/days/of/our/lives'
给定条件的期望输出(!!)
tax-march-donald-trump-protest-
条件:必须使用交替捕获组,必须捕获([\S]+) 或([\S]+?)/ 来捕获其他组,但如果它们不包含-,则忽略它们
我很清楚使用re.findall('([\-]*(?:[^/]+?\-)+)[\d]+', string) 或类似的东西会更好,但我想知道我是否可以使用[\S]+ 或([\S]+) 或([\S]+?)/ 并告诉正则表达式,如果那些被捕获,如果它包含/ 或不包含-,则忽略结果同时还使用了交替捕获组
我知道我不需要使用[\S]+ 或([\S]+),但我想看看是否有一个额外的指令可以让正则表达式拒绝这两个通常会捕获的某些字符。
【问题讨论】:
-
评论不用于扩展讨论;这个对话是moved to chat。
标签: python regex python-3.x