![](/img/trans.png)
[英]Python Regex inverse/negative match on a SINGLE line NOT on multiple lines, NOT USING SPLIT(), and NOT testing previous match groups
[英]How to split a string into multiple lines using regex before the pattern match
我有一個包含以下格式的 swift 數據的文件,需要使用 python 中的正則表達式將其拆分為多行。 原始文件:
ID Information
1 :20:Test1 :25:test2:28C:test3
所需的 Output:
ID Information
1 :20:Test1
1 :25:test2
1 :28C:test3
使用記事本++,我可以使用將“信息”列分成多行
查找: ^:[0-9]{2}:|\s:[0-9]{2}:|\s:[0-9]{2}[A-Za-z]{1}:
替換: \n$0
需要使用 python 復制相同的內容。 到目前為止,我嘗試了以下代碼,但結果不包含該模式。 它在模式匹配后分裂:
import re
s = ':20:Test1 :25:test2:28C:test3'
l = re.compile('^:[0-9]{2}:|\s:[0-9]{2}:|\s:[0-9]{2}[A-Za-z]{1}:').split(s)
結果: ['', 'Test1 ', 'test2 ', 'test3']
拆分字符串時,結果還應包含正則表達式模式。
這個模式怎么樣:
import re
s = ':20:Test1 :25:test2:28C:test3'
p = re.compile('(:[0-9A-z]{1,3}:)([0-9A-z]+)')
print(p.findall(s))
#[(':20:', 'Test1'), (':25:', 'test2'), (':28C:', 'test3')]
鑒於您有多種類型的 output,使用正則表達式的小邏輯可能更容易:
s='''\
ID Information
1 :20:Test1 :25:test2:28C:test3'''
import re
for line in s.splitlines():
if m:=re.search(r'^(\d+)([ \t]+)(:.*)',line):
data=re.findall(r'(:[^:]+:[^:]+(?=:|$))', m.group(3))
for e in data:
print(m.group(1)+m.group(2)+e.rstrip())
else:
print(line)
印刷:
ID Information
1 :20:Test1
1 :25:test2
1 :28C:test3
如所寫,僅 Python 3.8+。 如果您想要更早的 Python 3.X:
for line in s.splitlines():
m=re.search(r'^(\d+)([ \t]+)(:.*)',line)
if m:
...
您可以使用
import re
text = """ID Information
1 :20:Test1 :25:test2:28C:test3"""
valid_line_rx = r'^(\d+\s*)(:\d{2}[A-Za-z]?:.*)'
print( re.sub(valid_line_rx, lambda m:
"\n".join(["{}{}".format(m.group(1),x) for x in re.split(r'(?!^)(?=:\d{2}[A-Za-z]?:)', m.group(2))]),
text,
flags=re.M)
)
參見Python 演示,output:
ID Information
1 :20:Test1
1 :25:test2
1 :28C:test3
^(\d+\s*)(:\d{2}[A-Za-z]?:.*)
正則表達式匹配
^
- 行首(由於re.M
標志)(\d+\s*)
- 第 1 組:一個或多個數字,然后是 0 個或多個空格(:\d{2}[A-Za-z]?:.*)
- 第 2 組: :
,兩位數,一個可選字母和 aa :
以及盡可能多的除換行符以外的任何 0 個或多個字符. (??^)(:=?\d{2}[A-Za-z]::)
正則表達式匹配不是字符串開頭的位置,並且緊隨其后的是:
、2位數字、一個可選字母和a :
,並且此模式用於拆分上述正則表達式匹配的 Group 2 值。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.