Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using regex for multiple lines

Tags:

python

regex

What is the best way of extracting expressions for the following lines using regex:

Sigma 0.10 index = $5.00
beta .05=$25.00
.35 index (or $12.5)
Gamma 0.07

In any of the case, I want to extract the numeric values from each line (for example "0.10" from line 1) and (if available) the dollar amount or "$5.00" for line 1.

like image 537
James Hallen Avatar asked Dec 05 '25 14:12

James Hallen


2 Answers

import re
s="""Sigma 0.10 index = $5.00
beta .05=$25.00
.35 index (or $12.5)
Gamma 0.07"""
print re.findall(r'[0-9$.]+', s)

Output:

['0.10', '$5.00', '.05', '$25.00', '.35', '$12.5', '0.07']

More strict regex:

print re.findall(r'[$]?\d+(?:\.\d+)?', s)

Output:

['0.10', '$5.00', '$25.00', '$12.5', '0.07']

If you want to match .05 also:

print re.findall(r'[$]?(?:\d*\.\d+)|\d+', s)

Output:

['0.10', '$5.00', '.05', '$25.00', '.35', '$12.5', '0.07']
like image 57
perreal Avatar answered Dec 08 '25 03:12

perreal


Well the base regex would be: \$?\d+(\.\d+)?, which will get you the numbers. Unfortunately, I know regex in JavaScript/C# so not sure about how to do multiple lines in python. Should be a really simple flag though.

like image 23
sircodesalot Avatar answered Dec 08 '25 04:12

sircodesalot



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!