Regex to split phrases separated into columns by many whitespaces

Viewed 45

I'm hoping to get some regex assistance. I've got lines of columnar text that I'd like to split with regexes. Each column can be phrases of arbitrary characters, separated by a whitespace or maybe even two. Columns are separated by a larger number of whitespaces, perhaps at least 4.

Ultimately, I need to match a date if its in the second column.

Here's an example. I need the date in this column to be the group important_date

        Rain in Spain                                                   11/01/2000                                   90 Days

important_date should not match the date in this next line:

          Another                                                           line of text                             10/15/1990
# EXAMPLE:
import re

regex = r"(.*)\s(?P<important_date>\d{1,2}\/\d{1,2}\/\d{4}).*"

match_this = "        Rain in Spain                                                   11/01/2000                                   90 Days"

not_this = "          Another                                                           line of text                             10/15/1990"

print(f"Finding this date is good:{re.search(regex, match_this).group('important_date')}" )
print(f"But this one should throw an error:{re.search(regex,not_this).group('important_date')}")

I'm also comparing these regexes against lots of other lines of text with various structures, so this is why I don't want to just split on a string of " ". To know I've got the important_date, I need to know that the whole line looks like: one-column, second column is date, maybe another column after the date too.

Doing this with a single regex would also just fit much more easily into the rest of the application. I'm worried that line.split(" ") and checking the resulting list would interfere with other checks going on in this app.

I have not been able to figure out how to write the first part of the regex that captures words with no-more-than-2 spaces between them. Can I use lookaheads for this somehow?

Thank you!

2 Answers

Try this: (?m)^\s*(\w+\s)+\s+(?P<important_date>\d\d/\d\d/\d\d\d\d).*$ (https://regex101.com/r/PnIU3e/3).

I assume that the first column consists of words separated by single spaces, and is separated from the second column by more than one space.

You can split on fields of 2 or more spaces and only use the data if it is the second field:

for x in (match_this, not_this):
    te=re.split(r'[ \t]{2,}',x)
    if re.match(r'\d{1,2}\/\d{1,2}\/\d{4}', te[2]):
        # you have an important date
        print(te[2])
    else:
        # you don't
        print('no match')   
Related