Python:按特定模式拆分 [英] Python: Splitting by certain pattern

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

问题描述

我有以下内容

str = '[5.955894, 45.817792], [10.49238, 45.817792], [10.49238, 47.808381], [5.955894, 47.808381]'

我想拆分它以便我有一个像

这样的字符串数组

['[5.955894, 45.817792]', '[10.49238, 45.817792]', ...]

这样 [...] 对象是数组的元素.包含封闭的 [ 和 ] 很重要.我已经走了这么远:

re.split('\D,\s\D', str)

但这给了我:

['[5.955894, 45.817792', '10.49238, 45.817792', '10.49238, 47.808381', '5.955894, 47.808381']

不是我想要的.

解决方案

我更喜欢使用 re.findall 并指定我想要的,而不是试图描述分隔符对于 re.split

<预><代码>>>>s = '[5.955894, 45.817792], [10.49238, 45.817792], [10.49238, 47.808381], [5.955894, 47.808381]'>>>re.findall(r"\[[^\]]*\]",s)['[5.955894, 45.817792]', '[10.49238, 45.817792]', '[10.49238, 47.808381]', '[5.955894, 47.808381]'

  1. \[ 匹配 [
  2. [^\]]* 匹配除 ] 以外的任何内容
  3. \] 匹配 ]

I have the following

str = '[5.955894, 45.817792], [10.49238, 45.817792], [10.49238, 47.808381], [5.955894, 47.808381]'

I want to split it so that I have an array of strings like

['[5.955894, 45.817792]', '[10.49238, 45.817792]', ...]

So that the [...] objects are elements of the array. It is important that the enclosing [ and ] are included. I've come so far:

re.split('\D,\s\D', str)

But that gives me:

['[5.955894, 45.817792', '10.49238, 45.817792', '10.49238, 47.808381', '5.955894, 47.808381]']

Not really what I want.

解决方案

I prefer to use re.findall and specify what I want instead of trying to describe the delimiter for re.split

>>> s = '[5.955894, 45.817792], [10.49238, 45.817792], [10.49238, 47.808381], [5.955894, 47.808381]'
>>> re.findall(r"\[[^\]]*\]",s)
['[5.955894, 45.817792]', '[10.49238, 45.817792]', '[10.49238, 47.808381]', '[5.955894, 47.808381]']

  1. \[ matches [
  2. [^\]]* matches anything but ]
  3. \] matches ]

这篇关于Python:按特定模式拆分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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