Python正则表达式匹配除另一个模式之外的所有开始序列

2024-04-20 01:29:46 发布

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

目标:返回匹配所有开始序列但不包括大小序列的分组。你知道吗

## 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
]

Tags: orofnamehere模式groupanother序列
2条回答

我想这会给你想要的:

[re.match(r"^([^x]+[\-_]\s?)?(.*$)", s).groups() for s in strs]

regex的解释:从字符串的开头开始,查找一个或多个不是x的字符,这些字符后跟连字符或下划线,可能后跟空格。那是第一组,可以是零或一个。第二组是其他的。你知道吗

编辑:

假设字符串中可以包含除字母x以外的数字,则可以将代码修改为:

[re.match(r"^([^a-zA-Z]+[\-_]\s?)?(.*$)", s).groups() for s in strs]

我想你误解了lookaheads的用法。这种模式应该行得通

((?:(?!\d{1,3}x\d{1,3})[0-9\- ._/])*)(.*)

Regular expression visualization

Debuggex Demo

如果你想要一个解释,因为我知道这是一个恶心的正则表达式,只要问:)

相关问题 更多 >