【问题标题】:How to print out the substring between two "|" in python?如何打印出两个“|”之间的子字符串在蟒蛇?
【发布时间】:2020-08-08 09:28:03
【问题描述】:

我正在尝试获取两个“|”之间的子字符串(空格、“.”和 1)。

我尝试了以下代码:

f = open('test.txt', 'r')

with f:
    data = f.read()
    for line in data.splitlines():
        if line.startswith('Y='):
            m = re.search('| (.+?) |', line)
            if m:
                found = m.group(1)
            print(found)

但唯一打印出来的是“无”。

test.txt 中的文本

【问题讨论】:

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


    【解决方案1】:

    管道|是正则表达式中的特殊字符。

    您可以通过将它们括在括号中或转义它们来将它们视为简单字符。

    m = re.search('[|] (.+?) [|]', line)
    # or 
    m = re.search(r'\| (.+?) \|', line)
    

    它现在应该可以按您的预期工作了。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-01-01
      • 2020-03-23
      • 2021-01-22
      • 2017-01-06
      • 2021-03-23
      • 1970-01-01
      • 2022-11-16
      • 2022-01-26
      相关资源
      最近更新 更多