【问题标题】:ReGex Python brackets and parenthesis正则表达式 Python 括号和圆括号
【发布时间】:2019-01-30 00:23:54
【问题描述】:

我有几个表单的输入

intput1: 'some text1 \(blabla1\) some text2 \[blabla2\] some text3 \[blabla3\]'
intput2: '\(bla1\) some text'
intput3: '\[bla2\] some text and \[bla3\]'

等等。

((...)、[...]的个数和顺序不固定)

对于每个输入 i 我想要一个列表 output_i 的形式

output_1=[some text1, \(blabla1\),some text2, \[blabla2\], some text3]
output_2=[\(bla1\),some text]
output_3=[\(bla2\),some text and, \[bla3\]]

我尝试使用以下内容:

totreat = re.split(r'\\\((.*?)\\\)|\\\[(.*?)\\\]|\\\)(.*?)\\\(|\\\](.*?)\\\[|\\\)(.*?)\\\[|\\\](.*?)\\\(',src)

没有成功

【问题讨论】:

    标签: python regex python-3.x pattern-matching brackets


    【解决方案1】:

    给定一个输入字符串i,你用空格分割字符串,然后可以使用itertools.groupby根据每个子字符串是否以括号开头和结尾来分组输出:

    from itertools import groupby
    [' '.join(g) for _, g in groupby(i.split(), key=lambda s: s.startswith(('\(', '\[')) and s.endswith(('\)', '\]')))]
    

    这将返回,给定您的输入字符串分别来自 intput1intput2intput3

    ['some text1', '\\(blabla1\\)', 'some text2', '\\[blabla2\\]', 'some text3', '\\[blabla3\\]']
    ['\\(bla1\\)', 'some text']
    ['\\[bla2\\]', 'some text and', '\\[bla3\\]']
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-07-18
      • 2012-04-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-29
      相关资源
      最近更新 更多