Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/16.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_Split - Fatal编程技术网

在Python中按模式拆分字符串(不在开头或结尾)

在Python中按模式拆分字符串(不在开头或结尾),python,regex,split,Python,Regex,Split,我试图在Python中同时出现连字符和数字时拆分字符串 示例- 'ABC7-8-1234: Veggie - RESTRICTED (1)' -> ['ABC7','234: Veggie - RESTRICTED (1)'] 'AB-WALT-9-2065: Application (6)` -> ['AB-WALT', '065: Application (6)'] 在步骤1中,我尝试将re.split()按“-”拆分。但它不起作用 name = re.split(r

我试图在Python中同时出现连字符和数字时拆分字符串

示例-

'ABC7-8-1234: Veggie - RESTRICTED (1)' -> ['ABC7','234: Veggie - RESTRICTED (1)']
'AB-WALT-9-2065: Application (6)` -> ['AB-WALT', '065: Application (6)']
在步骤1中,我尝试将re.split()按“-”拆分。但它不起作用


    name = re.split(r"\B-", string)

我将
['ABC7-8-1234:Veggie','RESTRICTED(1)]
作为输出,而不是
['ABC7','8','1234:Veggie','RESTRICTED(1)]

第2步是检查连字符和数字的出现情况。类似-[0-9]

如何解决此问题?

有关完整答案:

st='ABC7-8-1234: Veggie - RESTRICTED (1)'
st=re.search('(.*):.*', st).group(1)
re.split('-\d-', st)

Out[26]: ['ABC7', '1234']

您可以首先使用
拆分字符串,并获取第0个索引,然后使用正则表达式
-\d+-
拆分该字符串,您应该会得到您在问题中发布的所需值。看看这段Python代码

import re

arr = ['ABC7-8-1234: Veggie - RESTRICTED (1)', 'AB-WALT-9-2065: Application (6)']

for s in arr:
 print(re.split(r'-\d+-', re.split(':', s)[0]))
import re

arr = ['ABC7-8-1234: Veggie - RESTRICTED (1)', 'AB-WALT-9-2065: Application (6)']

for s in arr:
 m = re.search(r'^(.+?)-\d+-([^:]+)', s)
 if m:
  print([m.group(1), m.group(2)])
印刷品

['ABC7', '1234']
['AB-WALT', '2065']
['ABC7', '1234']
['AB-WALT', '2065']
作为一种替代方法,您也可以使用此正则表达式并从group1和group2捕获您的值

^(.+?)-\d+-([^:]+)

Python代码

import re

arr = ['ABC7-8-1234: Veggie - RESTRICTED (1)', 'AB-WALT-9-2065: Application (6)']

for s in arr:
 print(re.split(r'-\d+-', re.split(':', s)[0]))
import re

arr = ['ABC7-8-1234: Veggie - RESTRICTED (1)', 'AB-WALT-9-2065: Application (6)']

for s in arr:
 m = re.search(r'^(.+?)-\d+-([^:]+)', s)
 if m:
  print([m.group(1), m.group(2)])
印刷品

['ABC7', '1234']
['AB-WALT', '2065']
['ABC7', '1234']
['AB-WALT', '2065']

将正则表达式与非捕获组(?:)一起使用:

保留分隔符模式中的数字:

re.split(r"-(\d)",s1)                                                  
Out: ['ABC7', '8', '', '1', '234: Veggie - RESTRICTED (1)']
如果存在连续模式,则会得到空字符串

使用正向前瞻:

re.split(r"-(?=\d)",s1)                                                
Out: ['ABC7', '8', '1234: Veggie - RESTRICTED (1)']

尝试将该
\B
替换为
\d
\d
捕获一个数字。
重新拆分('-\d-',st)
['ABC7','1234:Veggie-RESTRICTED(1)'”
作为输出。在那里,你可以找到一种方法来保存你所需要的东西。在你想要拆分的字符串后面总是有一个冒号吗?@JuanC是的,总是有一个冒号。re.split(“-\d”,string)应该对你有帮助