Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python regex for diffstat output

Tags:

python

regex

I would like to match the following strings using python regex and extract the numbers.

1 file changed, 1 insertion(+), 1 deletion(-)
2 files changed, 10 insertions(+), 10 deletions(-)
1 file changed, 1 insertion(+)
1 file changed, 2 deletions(-)

So i though to use the named groups in python regex and look ahead patterns. But that is not working as expected.

#!/usr/bin/python
import re
pat='\s*(\d+).*changed,\s+(\d*)(?P<in>=\s+insertion).*(\d+)(?P<del>=\s+deletion.*')
diff_stats = re.compile(pat)
obj = diff_stats.match(line)
like image 456
Dinesh Reddy Avatar asked Aug 20 '26 12:08

Dinesh Reddy


1 Answers

Remove = from named capture group.. Also.. your last group is not closed!

\s*(\d+).*changed,\s+(\d*)(?P<in>\s+insertion).*(\d+)(?P<del>\s+deletion).*
                                 ↑                           ↑          ↑

See DEMO

Edit: Improved regex for + and - too and named capture of digits:

\s*(\d+)\s+files?\s+changed,\s*((?P<in>\d+)\s*(insertions?)\([+-]\))?,?\s*((?P<del>\d+)\s*(deletions?)\([+-]\))?

See DEMO

like image 89
karthik manchala Avatar answered Aug 23 '26 03:08

karthik manchala



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!