Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/google-maps/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 正则表达式:使用“拆分”字符/&引用;_Python_Regex - Fatal编程技术网

Python 正则表达式:使用“拆分”字符/&引用;

Python 正则表达式:使用“拆分”字符/&引用;,python,regex,Python,Regex,我有以下字符串,例如: ['2300LO/LCE','2302KO/KCE'] 我想要这样的输出: ['2300LO','2300LCE','2302KO','2302KCE'] 在Python中如何使用正则表达式 谢谢 您可以尝试以下方法: list1 = ['2300LO/LCE','2302KO/KCE'] list2 = [] for x in list1: a = x.split('/') tmp = re.findall(r'\d+', a[0])

我有以下字符串,例如:
['2300LO/LCE','2302KO/KCE']

我想要这样的输出:
['2300LO','2300LCE','2302KO','2302KCE']

在Python中如何使用正则表达式


谢谢

您可以尝试以下方法:

list1 = ['2300LO/LCE','2302KO/KCE']
list2 = []

for x in list1:        
    a = x.split('/')

    tmp = re.findall(r'\d+', a[0]) # extracting digits
    list2.append(a[0])
    list2.append(tmp[0] + a[1])

print(list2)

您可以制作一个简单的生成器,为每个字符串生成对。然后,您可以使用
itertools.chain()


这有额外的好处,或者可以使用像
'2300LO/LCE/XX/CC'
这样的字符串,这将为您提供
['2300LO','2300LCE','2300XX','2300CC',…]

这可以通过简单的字符串拆分来实现

由于您使用regex询问输出,下面是您的答案

list1 = ['2300LO/LCE','2302KO/KCE']

import re
r = re.compile("([0-9]{1,4})([a-zA-Z].*)/([a-zA-Z].*)")
out = []
for s in list1:
  items = r.findall(s)[0]
  out.append(items[0]+items[1])
  out.append(items[2])

print(out)
正则表达式的说明-(4位数字),后跟(任何字符),后跟a/和(其余字符)


它们与()一起分组,因此当您使用find all时,它将成为单个元素

这将为您提供一个
索引器
<代码>tmp是一个单一元素列表。
list1 = ['2300LO/LCE','2302KO/KCE']

import re
r = re.compile("([0-9]{1,4})([a-zA-Z].*)/([a-zA-Z].*)")
out = []
for s in list1:
  items = r.findall(s)[0]
  out.append(items[0]+items[1])
  out.append(items[2])

print(out)