r – Regex Finding values across multiple lines

I have a file that sometimes has additional values. Most people have a single SSN, but some people have multiple SSNs and they are separated on multiple lines. What is the regex I need for this? My desired output is an R list of SSNs.

The source file was read in using read_lines() as object f:

dput(f)
c("------------ Phase 1 ------------", "DOB:    12/23/23", "SSN:    123456766", 
"        123456777", "        123456788", "        123456799", 
"        123456700", "Address: 5 Green Lane", "", "", "------------ Phase 2 ------------", 
"DOB:    12/33/23", "SSN:    223456766", "Address: 22 Blue Lane", 
"")

and as shown in the text file as:

------------ Phase 1 ------------  
DOB:    12/23/23  
SSN:    123456766  
        123456777  
        123456788  
        123456799  
        123456700  
Address: 5 Green Lane  
  
  
------------ Phase 2 ------------  
DOB:    12/33/23  
SSN:    223456766  
Address: 22 Blue Lane  

My current regex is:
“SSN:\s+\d{9}(\n\s\d{9})?”
and I’ve tried various regex options like dotall and multiline without success.

Regarding output structure, my preference is as simple as possible, ideally as a data.frame. (I’m looking for suggestions from you as to best practices). I realize that’s awkward for multiples in a data.frame as it would have to extend across multiple columns. Otherwise a list would be able to handle multiples, or a single cell in a data.frame separated by commas.

Thanks

Read more here: Source link