Python基于条件分割字符串 [英] Python split string based on conditional

查看:76
本文介绍了Python基于条件分割字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果逗号前面是某个正则表达式,我想使用逗号分隔符分割字符串.考虑我的字符串采用以下格式的情况:(一堆可能有逗号的东西)FOO_REGEX,(其他可能有逗号的东西)FOO_REGEX,..."我想用逗号分割字符串,但前提是它们前面有 FOO_REGEX:[(一堆可能有逗号的东西)FOO_REGEX",(其他可能有逗号的东西)FOO_REGEX",tc.].

作为一个具体的例子,考虑拆分以下字符串:

你好!$$asdf,我是 foo,bar $$jkl,很酷"

进入这个包含三个字符串的列表:

["你好!$$asdf","我是 foo, bar $$jkl",凉爽的"]

在python中有没有简单的方法可以做到这一点?

解决方案

您可以使用 re.findall 而不是 re.split.

<预><代码>>>>进口重新>>>s = "你好!$$asdf,我是 foo,bar $$jkl,很酷">>>[j for i in re.findall(r'(.*?\$\$[^,]*),\s*|(.+)', s) for j in i if j]['你好!$$asdf', '我是 foo, bar $$jkl', 'cool']

使用外部regex 模块来支持可变长度的lookbehind,因为re 将不支持可变长度的后视断言.

<预><代码>>>>导入正则表达式>>>s = "你好!$$asdf,我是 foo,bar $$jkl,很酷">>>regex.split(r'(?<=\$\$[^,]*),\s*', s)['你好!$$asdf', '我是 foo, bar $$jkl', 'cool']

I want to split strings using a comma delimiter if the comma is preceded by a certain regex. Consider the case where my strings are in the format: "(bunch of stuff that might have commas) FOO_REGEX, (other stuff that might have commas) FOO_REGEX, ..." and I want to split the string on commas, but only if they're preceded by FOO_REGEX: ["(bunch of stuff that might have commas) FOO_REGEX", "(other stuff that might have commas) FOO_REGEX", tc.].

As a concrete example, consider splitting the following string:

"hi, hello! $$asdf, I am foo, bar $$jkl, cool" 

into this list of three strings:

["hi, hello! $$asdf", 
"I am foo, bar $$jkl", 
"cool"]

Is there any easy way to do this in python?

解决方案

You could use re.findall instead of re.split.

>>> import re
>>> s = "hi, hello! $$asdf, I am foo, bar $$jkl, cool"
>>> [j for i in re.findall(r'(.*?\$\$[^,]*),\s*|(.+)', s) for j in i if j]
['hi, hello! $$asdf', 'I am foo, bar $$jkl', 'cool']

OR

Use external regex module to support variable length lookbehind since re won't support variable length look-behind assertions.

>>> import regex
>>> s = "hi, hello! $$asdf, I am foo, bar $$jkl, cool"
>>> regex.split(r'(?<=\$\$[^,]*),\s*', s)
['hi, hello! $$asdf', 'I am foo, bar $$jkl', 'cool']

这篇关于Python基于条件分割字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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