Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RegEx to span multiple lines

I have a text file with loads of unstructured data from which I'm trying to pull names and birthdates using 1 RegEx. The wall I've hit as of now is that the dates can end in one line and continue in another and re.DOTALL doesn't seem to be working. The format of the data I want is always:

last name, middle name(sometimes), first name, f. DD-MM-YYYY

This is my RegEx:

re.findall(r'\w+,*\sf\.\s\d\d-\d\d-\d\d\d\d', re.DOTALL):

This doesn't get the below line breaks:

Smith, John,

f. 25-12-1990

or only first part of below:

Smith, John, f. 25-12-

1990

Smith, John, f. 25-

12-1990

like image 451
pam_param Avatar asked Jan 20 '26 04:01

pam_param


1 Answers

If you want all the options to match the dates on possible newlines, you could repeat the whitespace char 0+ times between all the characters.

Note that in your pattern you are repeating the comma 0+ times ,* instead of the \s

Using re.DOTALL makes the . match a newline, but in your pattern you are not using a dot, only a literal dot \.

The \s will match a whitespace char including a newline. In your data there are multiple newlines between the date part. You could also use [\r\n]* to match the newlines in between.

\w+,\s*f\s*\.\s*\d\s*\d\s*-\s*\d\s*\d\s*-\s*\d\s*\d\s*\d\s*\d

Regex demo | Python demo

If the break is only after the hyphen:

\w+,\s*f\s*\.\s*\d\d-\s*\d\d-\s*\d\d\d\d

Regex demo | Python demo

like image 190
The fourth bird Avatar answered Jan 21 '26 19:01

The fourth bird



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!