簡體   English   中英

如何在兩個“|”之間打印出 substring 在 python 中?

[英]How to print out the substring between two “|” in python?

我試圖在兩個“|”之間獲取 substring(空格、“.”和 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 中的文本

試圖閱讀這段文字

pipe | 是正則表達式中的特殊字符。

您可以通過將它們括在方括號或 escaping 中來將它們視為簡單字符。

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

它現在應該可以按您的預期工作。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM