Regex hyphen causing issues

Viewed 38

I'm trying to use python to extract invoice info from a text file. The items always start with a quantity (1 x, 2 x, etc) and end with a part number, for various reasons the descriptions can differ even for the same item. The following regex seems to pull out most of the entries, but fails when there is a hyphen '-' in the description.

Regex:

^([0-9]+\sx) [\w\s\r\n®.,]* [0-9]{3}-\d[A-Z]\d+(-AB)?  

I'm struggling to work out how to modify the regex to deal with this. I though adding (\s-\s) in would help, but the regex then seems to match parts of different entries rather than the individual ones. I'm sure there are more efficient ways of writing the regex, but I don't use them that often, so getting this far was an achievement. Any pointers gratefully received.

Example entries shown below. With the above regex, the middle one doesn't get matched unless I delete the '-'

1 x Product® 100, Low range items

3,456.00 USD

Cat. No. 012-3A45


1 x Product® 100. Low range items - LRI

123,456.00 USD

Part. no. 201-5G95


2 x Product Mid Range Items

7,654.00 USD

Art. no. 001-8Q147-AB
1 Answers

You can add a hyphen and make the pattern non greedy

^([0-9]+\sx) [-\w\s®.,]*? [0-9]{3}-\d[A-Z]\d+(-AB)?

Regex demo

Note that \s also matches a newline.

Related