簡體   English   中英

在正則表達式后添加新行

[英]Add a new line after a regex

每當我的程序找到一個正則表達式時,我都想添加一個新行。 我想保留正則表達式,並且在它之后僅換行。 .txt文件讀取文本。 我可以找到該正則表達式,但是當我嘗試添加新行時,它會在實際輸出中返回,如下所示。 我已經嘗試解決了幾個小時,很樂意提供幫助。

這是一個簡單的示例:

在:

STLB 1234 444 text text text
STLB 8796 567 text text text

在以下位置編輯:

STLB 1234 444text text text

STLB 8796 567text text text

想要的輸出:

STLB 1234 444
text text text
STLB 8796 567
text text text

實際輸出:

(STLB.*\d\d\d) 

(STLB.*\d\d\d) 

這是我的代碼:

stlb_match = re.compile('|'.join(['STLB.*\d\d\d']))

with open(in_file5, 'r', encoding='utf-8') as fin5, open(out_file5, 'w', encoding='utf-8') as fout5:
    lines = fin5.read().splitlines()

    for i, line in enumerate(lines):
        matchObj1 = re.match(start_rx, line)

        if not matchObj1:
            first_two_word = (" ".join(line.split()[:2]))

            if re.match(stlb_match,line):
                line =re.sub(r'(STLB.*\d\d\d)', r'(STLB.*\d\d\d)'+' \n', line)
            elif re.match(first_two_word, line):
                line = line.replace(first_two_word, "\n" + first_two_word)

        fout5.write(line)

假設各行的格式始終為STLB <number> <number> <text> ,則可以執行以下操作:

with open(in_file5, 'r', encoding='utf-8') as fin5, open(out_file5, 'w', encoding='utf-8') as fout5:
    for l in fin5:
      l = re.sub(r'(STLB\s*\d+\s*\d+)\s*', r'\1\n', l)

      fout5.write(l)
      fout5.write('\n')

輸入項

STLB 1234 444 text text text
STLB 8796 567 text text text

輸出量

STLB 1234 444
text text text

STLB 8796 567
text text text

注意RegEx末尾的\\s* ,但是捕獲組在此之前結束,因此那些尾部的空格被忽略了。

使用列表理解writelines

with open(in_file5, 'r', encoding='utf-8') as fin5, open(out_file5, 'w', encoding='utf-8') as fout5:
    fout5.writelines([re.sub(r'(STLB\s*\d+\s*\d+)\s*', r'\1\n', l) for l in fin5])

讓我知道這是否適合您

您的替換零件是錯誤的,您不能在其中放置正則表達式。 改成:

line = 'STLB 1234 444 text text text'
line = re.sub(r'(STLB.*\d\d\d)', r"\1\n", line)
print line

輸出:

STLB 1234 444
 text text text

要么:

line = re.sub(r'(STLB.*\d\d\d) ', r"\1\n", line)

如果要刪除第二行開頭的空格

暫無
暫無

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

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