【问题标题】:python: parse substring in brackets from stringpython:从字符串中解析括号中的子字符串
【发布时间】:2019-06-21 05:22:55
【问题描述】:

在括号中解析这个字符串的pythonic方法是什么:

txt = 'foo[bar]'

得到结果:

bar

我尝试了什么:

我将如何解决它,我认为它不是很优雅:

result = txt.split('[')[1].split(']')[0]

我强烈认为有一个库或方法可以为此提供更容错和优雅的解决方案。这就是我提出这个问题的原因。

【问题讨论】:

标签: python parsing


【解决方案1】:

使用正则表达式。

例如:

import re

txt = 'foo[bar]'
print(re.findall(r"\[(.*?)\]", txt))

输出:

['bar']

【讨论】:

    【解决方案2】:

    多种方式之一,使用slicing

    print(txt[4:].strip("[]"))
    

    import re
    
    txt = 'foo[bar]'
    
    m = re.search(r"\[([A-Za-z0-9_]+)\]", txt)
    print(m.group(1))
    

    输出:

    bar
    

    【讨论】:

      【解决方案3】:

      另一种切片方法,使用str.index 查找开始和结束分隔符的位置。一旦你得到一个 Python 切片,你可以把它当作列表中的索引,除了切片不只是给出单个字符,而是从开始到结束的字符范围。

      def make_slice(s, first, second):
          floc = s.index(first)
          sloc = s.index(second, floc)
          # return a Python slice that will extract the contents between the first
          # and second delimiters
          return slice(floc+1, sloc)
      
      txt = 'foo[bar]'
      
      slc = make_slice(txt, '[', ']')
      print(txt[slc])
      

      打印:

      bar
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-11-18
        • 1970-01-01
        • 2014-05-20
        • 2016-08-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多