Python RegExp-如何删除空间

Python RegExp-如何删除空间,python,regex,Python,Regex,您使用的[…]语法不正确;这是一个字符类,一组可以匹配的字符。该类中列出的任何一个字符都是匹配的,因此要么是空格,要么是(字符,要么是P或);那个空间会很好 使用非捕获组(而不是字符类)使额外文本成为可选文本,并为您想要的零件使用捕获组: s = "LEV606 (P), LEV230 (P)" #Expected result: ['LEV606', 'LEV230'] # First attempt In [3]: re.findall(r"[A-Z]{3}[0-9]{3}[ \(P\)]

您使用的
[…]
语法不正确;这是一个字符类,一组可以匹配的字符。该类中列出的任何一个字符都是匹配的,因此要么是空格,要么是
字符,要么是
P
;那个空间会很好

使用非捕获组(而不是字符类)使额外文本成为可选文本,并为您想要的零件使用捕获组:

s = "LEV606 (P), LEV230 (P)"
#Expected result: ['LEV606', 'LEV230']

# First attempt
In [3]: re.findall(r"[A-Z]{3}[0-9]{3}[ \(P\)]?", s)
Out[3]: ['LEV606 ', 'LEV230 ']

# Second attempt. The 'P' is not mandatory, can be other letter.
# Why this doesn't work?
In [4]: re.findall(r"[A-Z]{3}[0-9]{3}[ \([A-Z]{1}\)]?", s)
Out[4]: []

# Third attempt
# White space is still there. Why? I want to remove it from the answer
In [5]: re.findall(r"[A-Z]{3}[0-9]{3}[\s\(\w\)]?", s)
Out[5]: ['LEV606 ', 'LEV230 ']
演示:

re.findall(r"([A-Z]{3}[0-9]{3})(?: \(P\))?", s)
>>> import re
>>> s = "LEV606 (P), LEV230 (P)"
>>> re.findall(r"([A-Z]{3}[0-9]{3})(?: \(P\))?", s)
['LEV606', 'LEV230']