Search the specfic substring with a pattern format having last occurrence within a raw text

Viewed 58

I have a string like:

Location: FD130 New York GA Unit Serial Purchase Order Sales Order Make Model Amount Tax Total 12345566 Location: FD130 Roswell GA Unit Serial Purchase Order Sales Order Make Model Amount Tax Total 0130029964 

When i trying regex like to get the location of specified serial no.(34573). Regex: 'Location:(.*)?Unit(.*?)0130029964

Then it giving the whole string string with location and ending with 34573.

The expected output is FD130 New York GA when i pass 0130029964 serial id.

Is there any function in python for getting the first backward sub-string location from given serial no.

1 Answers

You can match location unit the first occurrence of unit using a tempered greedy token approach to not cross matching either location: unit or format.

Then optionally match format and match till the specific number without crossing matching location: again.

\blocation:\s*((?:(?!location:|unit|format).)+) (?:format )?unit (?:(?!location:).)+\b12345566\b

Regex demo

Related