Capture email address within non-capturing group RegEx

Viewed 61

I'm new to regex and am really struggling with how to specify a specific range of data to parse with a non-capturing group and then filter that data with a capturing group.

Specifically, I am using Invoice2Data to parse pdf invoices and need to set up a yaml file for my parsing template. The yaml file uses regex to set up the parsing template for invoice2data.

For example, say I have an invoice. There are multiple email addresses on the page, but I only want to capture the email that comes after 'Invoice for":

Invoice for
John Doe
555 Nowhere Ave
johndoe@email.com
555.555.5555

I know I can capture just these lines with something like: (?i)For\s(?:^(?:.*\n){4}) which returns:

John Doe
555 Nowhere Ave
johndoe@email.com
555.555.5555

The problem is, I don't know how to parse this non-capturing group to only capture the email, for example. I have this regex to find the email: ([a-zA-Z0-9._-]+@[a-zA-Z0-9._-]+\.[a-zA-Z0-9_-]+) but that on its own will include all emails in the invoice. Another problem is that not all invoices have an address so the actual line number might be different depending on the invoice.

How do I mix: (?i)For\s(?:^(?:.*\n){4}) and ([a-zA-Z0-9._-]+@[a-zA-Z0-9._-]+\.[a-zA-Z0-9_-]+) to only pull the email from that specific section of the invoice?

1 Answers

You can use a pattern that matches Invoice for followed by all the lines that do not start with an email address like pattern or | Invoice for using a negative lookahead (?!

Checking for Invoice for in the lookahead prevents matching an email address for the wrong Invoice, as the email address can be optional.

Then capture in group 1 the email address using your specific pattern.

^Invoice for(?:\r?\n(?![^\s@]+@[^\s@]|Invoice for\b).*)*\r?\n([a-zA-Z0-9._-]+@[a-zA-Z0-9._-]+\.[a-zA-Z0-9_-]+)

Regex demo

Or using your full email pattern in the negative lookahead as well

^Invoice for(?:\r?\n(?![a-zA-Z0-9._-]+@[a-zA-Z0-9._-]+\.[a-zA-Z0-9_-]|Invoice for\b).*)*\r?\n([a-zA-Z0-9._-]+@[a-zA-Z0-9._-]+\.[a-zA-Z0-9_-]+)

Regex demo

Related