社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Python

如何使用Python基于正则表达式划分字符串

Ammad • 5 年前 • 1528 次点击  

我有下面提到的数据的Python字符串。

--- Data-['tag']-['cli'] command ---> show date:

Current time: 2020-03-12 11:36:37 PDT

--- Data-['tag']-['shell'] command ---> show version:

OS Kernel 64-bit  
[builder_stable]

--- Data-['tag']-['cli'] command ---> show host:

Model: New

我的python代码如下所示。

array = data.split("--- Data")

for word in array:
    print(word)

我希望带分隔符的数据按顺序返回。

第一个拆分结果应为:

--- Data-['tag']-['cli'] command ---> show date:

Current time: 2020-03-12 11:36:37 PDT

第二个分割结果如下:

--- Data-['tag']-['shell'] command ---> show version:

OS Kernel 64-bit  
[builder_stable]

等等。有什么帮助吗?

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/56097
 
1528 次点击  
文章 [ 1 ]  |  最新文章 5 年前
blhsing
Reply   •   1 楼
blhsing    5 年前

你可以用 re.findall 使用模式查找分隔符模式,然后惰性地匹配任何字符,直到下一个分隔符模式或字符串结尾:

import re

s = '''--- Data-['tag']-['cli'] command ---> show date:

Current time: 2020-03-12 11:36:37 PDT

--- Data-['tag']-['shell'] command ---> show version:

OS Kernel 64-bit  
[builder_stable]

--- Data-['tag']-['cli'] command ---> show host:

Model: New'''

delimiter = r'--- Data[^\n]*?:'
print(re.findall(r'{0}.*?(?={0}|$)'.format(delimiter), s, re.S))