Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

regex : Read number and character from end until space is encountered

Tags:

python

regex

I want to divide the line into a date, description, and amount. The last digits are the amount that can contain Cr. I have a line like the following:

Date       Description    Amount
13/03/2021    XYZ ABC 428.00 31,408.37 Cr
17/03/2021    ZOOM.US 111-222-333 WWW.ZOOM.U USD 5.29 841.18

The regex that I used is:

regex_filter = re.compile(r'(\d{2}/\d{2}/\d{4}) (.*?) ([\d,]+\.\d{2}) ')**

And what I got is:

Date - 13/03/2021
Description - XYZ ABC
Amount - 428.00

I want the amount to be 31,408.37 Cr and for the second one amount should be 841.18. So I want digits and characters up to a space reading from the end.

How can I get this?

like image 842
Shivam Avatar asked Jan 25 '26 13:01

Shivam


1 Answers

You may use this regex with anchors and optional group:

^(\d{2}/\d{2}/\d{4})\s+(.*?)\s+((?:\d+(?:,\d+)*\.\d{2})(?: Cr)?)$

RegEx Demo

RegEx Details:

  • ^: Start
  • (\d{2}/\d{2}/\d{4}): 1st capture group to match date
  • \s+: 1+ whitespaces
  • (.*?): 2nd capture group to match anything lazily for description
  • \s+: 1+ whitespaces
  • ((?:\d+(?:,\d+)*\.\d{2})(?: Cr)?): 3rd capture group to match amount. Inside, we are matching ending Cr in an optional non-capture group
  • $: End
like image 146
anubhava Avatar answered Jan 28 '26 04:01

anubhava



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!