【问题标题】:How to remove strings from in between brackets with regex...python [closed]如何使用正则表达式从括号之间删除字符串... python [关闭]
【发布时间】:2016-05-11 22:47:21
【问题描述】:

我需要从提取的字段中提取一个包含单词的字符串:

[[cat]][[dog]][[mouse]][[apple]][[banana]][[pear]][[plum]][[pool]]

所以我需要:cat dog mouse apple banana pear plum pool

我已经尝试了 2 个小时来为此创建一个正则表达式。

我得到的最好的是(?<=[[]\S)(.*)(?=]]) 这让我明白了:

cat]][[dog]][[mouse]][[apple]][[banana]][[pear]][[plum]][[pool

有什么想法吗?谢谢!

【问题讨论】:

  • 一个简单的字符搜索就可以了。 /[a-z]+/gDemo
  • 双括号可以嵌套吗?
  • 这看起来确实像一个 XY 问题,您创建了一些格式错误的数据,现在需要获取信息。数据从何而来?

标签: python regex python-2.7 python-2.x


【解决方案1】:

这是re.finditer 的解决方案。让您的字符串为s。 这假设在 [[ 和 ]] 之间可以有任何内容。否则,@noob 的评论适用。

>>> [x.group(1) for x in re.finditer('\[\[(.*?)\]\]', s)]
['cat', 'dog', 'mouse', 'apple', 'banana', 'pear', 'plum', 'pool']

或者,使用环视和re.findall

>>> re.findall('(?<=\[\[).*?(?=\]\])', s)
['cat', 'dog', 'mouse', 'apple', 'banana', 'pear', 'plum', 'pool']

对于大字符串,finditer 版本在我计时替代方案时似乎稍快一些。

In [5]: s=s*1000
In [6]: timeit [x.group(1) for x in re.finditer('\[\[(.*?)\]\]', s)]
100 loops, best of 3: 3.61 ms per loop
In [7]: timeit re.findall('(?<=\[\[).*?(?=\]\])', s)
100 loops, best of 3: 5.93 ms per loop

【讨论】:

    【解决方案2】:

    简单的re.split 可以工作:

    >>> s = '[[cat]][[dog]][[mouse]][[apple]][[banana]][[pear]][[plum]][[pool]]'
    >>> import re
    >>> print re.split(r'[\[\]]{2,4}', s)[1:-1]
    ['cat', 'dog', 'mouse', 'apple', 'banana', 'pear', 'plum', 'pool']
    

    【讨论】:

      【解决方案3】:

      你必须用正则表达式来做吗?

      extract = "[[cat]][[dog]][[mouse]][[apple]][[banana]][[pear]][[plum]][[pool]]"
      word_list = [word for word in extract.replace('[', '').split(']') if word != '']
      print word_list
      

      输出:

      ['cat', 'dog', 'mouse', 'apple', 'banana', 'pear', 'plum', 'pool']
      

      现在正则表达式搞定了。只需找到不带括号的非空字符串。

      重新导入

      target = "[[cat]][[dog]][[mouse]][[apple]][[banana]][[pear]][[plum]][[pool]]"
      word_list = ' '.join(re.findall("[^\[\]]+", target))
      print word_list
      

      编辑后返回单个字符串,而不是字符串列表。

      【讨论】:

      • 不,我也没有。我一直在用它们解决一些我的清洁文本问题,所以我一直在尝试它们。不过,这确实有效。谢谢!
      猜你喜欢
      • 2020-05-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-11-07
      • 1970-01-01
      • 1970-01-01
      • 2021-11-24
      相关资源
      最近更新 更多