Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

how can i use re.findall to match a substring using python regex?

I have the following string variable called strSourceCode in python3.x,

'uint256 private constant _tTotal = 100000000 * 10**9;
uint256 private _rTotal = (MAX - (MAX % _tTotal));
_maxTxAmount = 300000000 * 10**9;'

I would like to match ‘100000000 * 10**’ and’300000000 * 10**’ and it should give me the following two lines as output using re.findall

uint256 private constant _tTotal = 100000000 * 10**9;
_maxTxAmount = 300000000 * 10**9;

Currently i have the following code:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

pattern = '^.*[0-9]0{4,}.*$'
matches = re.findall(pattern, strSourceCode, re.MULTILINE)

which falsely outputs as:

_maxTxAmount = 300000000 * 10**9;0000 * 10**9;

Any help would be appreciated.

>Solution :

We can try using re.findall here in multiline mode:

inp = """uint256 private constant _tTotal = 100000000 * 10**9;
uint256 private _rTotal = (MAX - (MAX % _tTotal));
_maxTxAmount = 300000000 * 10**9;"""

lines = re.findall(r'^.*\d+\s*\*\s*\d+\*\*\d+.*$', inp, flags=re.M)
print(lines)

This prints:

['uint256 private constant _tTotal = 100000000 * 10**9;',
 '_maxTxAmount = 300000000 * 10**9;']

The regex pattern used here attempts to find any line containing an integer multiplied by 10 to some integer power.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading