目标:返回匹配所有开始序列但不包括大小序列的分组。你知道吗
## List of strings and desired result
strs = [
'151002 - Some name', ## ('151002 - ', 'Some name')
'Another name here', ## ('', 'Another name here')
'13-10-07_300x250_NoName', ## ('13-10-07_', '300x250_NoName')
'728x90 - nice name' ## ('', '728x90 - nice name')
]
尝试的模式
## This pattern is close
##
pat = '''
^ ## From start of string
( ## Group 1
[0-9\- ._/]* ## Any number or divider
(?! ## Negative Lookahead
(?:\b|[\- ._/\|]) ## Beginning of word or divider
\d{1,3} ## Size start
(?:x|X) ## big or small 'x'
\d{1,3} ## Size end
)
)
( ## Group 2
.* ## Everthing else
)
'''
## Matching
[re.compile(pat, re.VERBOSE).match(s).groups() for s in strs]
尝试模式结果
[
('151002 - ', 'Some name'), ## Good
('', 'Another name here'), ## Good
('13-10-07_300', 'x250_NoName'), ## Error
('728', 'x90 - nice name') ## Error
]
我想这会给你想要的:
regex的解释:从字符串的开头开始,查找一个或多个不是x的字符,这些字符后跟连字符或下划线,可能后跟空格。那是第一组,可以是零或一个。第二组是其他的。你知道吗
编辑:
假设字符串中可以包含除字母x以外的数字,则可以将代码修改为:
我想你误解了lookaheads的用法。这种模式应该行得通
Debuggex Demo
如果你想要一个解释,因为我知道这是一个恶心的正则表达式,只要问:)
相关问题 更多 >
编程相关推荐