我有元素列表,其中包含数字,字母和特殊字符。
string = ['1 B, 14/A - P,1C,2A,21 C - A','3P,21B,2-A,1A','3C,2-W,ABC 200','3 Z,ABC 100 - BB','ABC 300,ABC 200','ABC 200,ABC 100','1c/A,2 - z']
string
['1 B, 14/A - P,1C,2A,21 C - A',
'3P,21B,2-A,1A',
'3C,2-W,ABC 200',
'3 Z,ABC 100 - BB',
'ABC 300,ABC 200',
'ABC 200,ABC 100',
'1c/A,2 - z']
我要提取与条件匹配的元素。
条件:-列表中的元素应为starting with the Matching number
或
以ABC (Matching number)
必填输出:
starting_with_one = ['1 B, 14/A - P,1C,2A,21 C - A','3P,21B,2-A,1A','3 Z,ABC 100 - BB','ABC 200,ABC 100','1c/A,2 - z']
['1 B, 14/A - P,1C,2A,21 C - A', ---> # Here `1 B ,14/A - P,1C` are contains the number 1
'3P,21B,2-A,1A', ---> # Here `1A` Contains the number 1
'3 Z,ABC 100 - BB', ---> # Here `ABC 100 - BB` Contains the number 1
'ABC 200,ABC 100', ---> # Here `ABC 100` Contains the number 1
'1c/A,2 - z'] ---> Here `1c/A' contains 1
starting_with_two = ['1 B, 14/A - P,1C,2A,21 C - A','3P,21B,2-A,1A','3C,2-W,ABC 200','ABC 300,ABC 200','ABC 200,ABC 100','1c/A,2 - z']
['1 B, 14/A - P,1C,2A,21 C - A',
'3P,21B,2-A,1A',
'3C,2-W,ABC 200',
'ABC 300,ABC 200',
'ABC 200,ABC 100',
'1c/A,2 - z']
我尝试过的事情:
搜索数字1
for i in string:
print(re.search(r"(^|[^\d])(1)", i))
<_sre.SRE_Match object; span=(0, 1), match='1'>
<_sre.SRE_Match object; span=(10, 12), match=',1'>
None
<_sre.SRE_Match object; span=(7, 9), match=' 1'>
None
<_sre.SRE_Match object; span=(11, 13), match=' 1'>
<_sre.SRE_Match object; span=(0, 1), match='1'>
答案 0 :(得分:1)
您可以使用
r'\b(?:ABC\s+)?1'
标识要保留的字符串。参见the regex demo。
详细信息
\b
-单词边界(?:ABC\s+)?
-可选的子字符串:ABC
,然后是1+个空格1
-1
字符。请参见Python demo:
import re
strs = ['1 B, 14/A - P,1C,2A,21 C - A','3P,21B,2-A,1A','3C,2-W,ABC 200','3 Z,ABC 100 - BB','ABC 300,ABC 200','ABC 200,ABC 100','1c/A,2 - z']
for s in strs:
if re.search(r'\b(?:ABC\s+)?1', s):
print(s)
输出:
1 B, 14/A - P,1C,2A,21 C - A
3P,21B,2-A,1A
3 Z,ABC 100 - BB
ABC 200,ABC 100
1c/A,2 - z