Home > other >  Using regex to split text into columns using
Using regex to split text into columns using

Time:07-14

I have several files with measurement date and time as shown as one text.

Measurement date: 22.06.06 14:03:49
Measurement date: 22.06.07 14:28:30
Measurement date: 22.06.09 07:42:38
Measurement date: 22.06.10 08:38:56
                 .
                 .
                 .

I want to split like below using regex

 date                              time
22.06.06                      14:03:49
22.06.07                      14:28:30
22.06.09                      07:42:38
22.06.10                      08:38:56

CodePudding user response:

You could use str.extract here:

df["date"] = df["text"].str.extract(r'\b(\d{2}\.\d{2}\.\d{2})\b')
df["time"] = df["text"].str.extract(r'\b(\d{2}:\d{2}:\d{2})\b')

CodePudding user response:

You don't really need regex (absolutely nothing wrong with regex, I just like to make things more simple for the future me), this example below uses only split:

fulltext = """Measurement date: 22.06.06 14:03:49
Measurement date: 22.06.07 14:28:30
Measurement date: 22.06.09 07:42:38
Measurement date: 22.06.10 08:38:56"""

print("Date \t\t Time")
for line in fulltext.split('\n'):
    print(f"{line.split()[2]}\t {line.split()[3]}")
  • Related