I have a file with the swift data in the below format that needs to be split into multiple lines using regular expression in python. Original file:
ID Information
1 :20:Test1 :25:test2:28C:test3
Desired Output:
ID Information
1 :20:Test1
1 :25:test2
1 :28C:test3
Using Notepad++ I am able to break the 'Information'column into multiple lines using
Find: ^:[0-9]{2}:|\s:[0-9]{2}:|\s:[0-9]{2}[A-Za-z]{1}:
Replace: \n$0
Need to replicate the same using python. So far i tried the below code but the result does not contain the pattern. It is splitting after the pattern match:
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)
Result: ['', 'Test1 ', 'test2 ', 'test3']
The result should also contain the regex pattern while splitting the string.
How about this pattern:
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')]
Given that you have multiple types of output, it may be easier to use a little logic with a regex:
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)
Prints:
ID Information
1 :20:Test1
1 :25:test2
1 :28C:test3
As written, that is Python 3.8+ only. If you want on an earlier Python 3.X:
for line in s.splitlines():
m=re.search(r'^(\d+)([ \t]+)(:.*)',line)
if m:
...
You may use
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)
)
See the Python demo , output:
ID Information
1 :20:Test1
1 :25:test2
1 :28C:test3
The ^(\d+\s*)(:\d{2}[A-Za-z]?:.*)
regex matches
^
- start of a line (due to re.M
flag) (\d+\s*)
- Group 1: one or more digits and then 0 or more whitespaces (:\d{2}[A-Za-z]?:.*)
- Group 2: :
, two digits, an optional letter and aa :
and then any 0 or more chars other than line break chars as many as possible. The (??^)(:=?\d{2}[A-Za-z]::)
regex matches a location that is not the start of string and is immediately followed with :
, 2 digits, an optional letter and a :
, and this pattern is used to split the Group 2 value of the above regex match.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.