我创建了一个正则表达式,用于匹配字符串中的第n次出现:
^(?:[^-]*-){2}([^-].*)但是,在regex工具中测试它没有得到100%匹配的解决方案:
例如:
产地:动物- XL运动前愤怒葡萄- 151克
预期:动物-动物愤怒XL运动前愤怒葡萄的愤怒
测试:动物-动物愤怒,XL Pre
产地: AST运动科学-R 200 - 90胶囊
预期: AST体育科学-R 200
测试: AST运动科学-R
据我所知,在上述正则表达式中,它是"-“的第二次匹配,我创建了下一个regex:
^(?:[^-]*\s-\s){2}([^-].*)但是它忽略了上面的例子。
我错过了什么完美的审判工作?
谢谢你帮忙。
发布于 2015-03-31 08:01:32
你可以试试下面的方法。
>>> s = 'ANIMAL - Animal Rage XL Pre-Workout Grape of Wrath - 151 Grams'
>>> s1 = 'AST Sports Science - R-ALA 200 - 90 Capsules'
>>> re.search(r'^(?:.*? - .*?)(?= - )', s).group()
'ANIMAL - Animal Rage XL Pre-Workout Grape of Wrath'
>>> re.search(r'^(?:.*? - .*?)(?= - )', s1).group()
'AST Sports Science - R-ALA 200'https://regex101.com/r/sJ9gM7/29
您也可以使用re.sub函数。
>>> re.sub(r' - (?:(?! - ).)*$', '', s)
'ANIMAL - Animal Rage XL Pre-Workout Grape of Wrath'
>>> re.sub(r' - (?:(?! - ).)*$', '', s1)
'AST Sports Science - R-ALA 200'这与<space>hyphen<space>分隔字符串的最后一部分匹配。将匹配替换为空字符串将为您提供所需的输出。
发布于 2015-03-31 07:52:30
看起来您正在寻找这个regex:(?m)^(.*)(\s+\-\s+(?!\s\-\s).*)$
Python中的示例代码:
str1 = 'ANIMAL - Animal Rage XL Pre-Workout Grape of Wrath - 151 Grams'
str2 = 'Anjolie Ayurveda - Rosemary Lavender and Neem Tulsi Soap Herbal Gift Box - CLEARANCE PRICED Nourish Your Skin & Awaken Your Senses'
print re.sub(r"(?m)^(.*)(\s+\-\s+(?!\s\-\s).*)$", "\g<1>", str1)
print re.sub(r"(?m)^(.*)(\s+\-\s+(?!\s\-\s).*)$", "\g<1>", str2)输出:
ANIMAL - Animal Rage XL Pre-Workout Grape of Wrath
Anjolie Ayurveda - Rosemary Lavender and Neem Tulsi Soap Herbal Gift Boxhttps://stackoverflow.com/questions/29363313
复制相似问题