由正则表达式拆分的 Python 后面看 [英] Python split by regex look behind

查看:30
本文介绍了由正则表达式拆分的 Python 后面看的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要使用以下代码拆分字符串:

导入重新x = re.split(r"(?<=,)","a,b,c,")打印 x

输出如下:

['a,b,c,']

我的预期是:

['a,','b,','c,']

更新

我使用答案中的解决方案:findall

我需要的是拆分新行(LF,0x0a)

导入重新a = '''aaaabbbbcccc'''x = re.findall(r"[^%s]+%s" % (0x0a,0x0a),a,re.DOTALL)打印 x

结果是:

<代码>[]

期望的是:

['aaaa\n','bbbb\n','cccc\n']

解决方案

在 python 中默认 re.split 函数不会在零宽度边界上进行拆分.所以改用 re.findall.

re.findall(r'\w+,', s)

更新:

<预><代码>>>>a = '''aaaabbbbcccc'''>>>re.findall(r".+\n?", a)['aaaa\n', 'bbbb\n', 'cccc\n']

I need to split a string with following code:

import re
x = re.split(r"(?<=,)","a,b,c,")
print x

The output looks like this:

['a,b,c,']

What I expected is:

['a,','b,','c,']

Update

I use the solution from Answer: findall

What my need is to split New Line(LF,0x0a)

import re
a = '''aaaa
bbbb
cccc
'''
x = re.findall(r"[^%s]+%s" % (0x0a,0x0a),a,re.DOTALL)
print x

The result is:

[]

What expect is there are:

['aaaa\n','bbbb\n','cccc\n']

解决方案

In python default re.split function won't do splitting on zero width boundaries. So use re.findall instead.

re.findall(r'\w+,', s)

Update:

>>> a = '''aaaa
bbbb
cccc
'''
>>> re.findall(r".+\n?", a)
['aaaa\n', 'bbbb\n', 'cccc\n']

这篇关于由正则表达式拆分的 Python 后面看的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆