Py学习  »  Python

我怎样才能使用re。findall使用python正则表达式匹配子字符串?

Abid • 3 年前 • 1389 次点击  

在python3中,我有一个名为strSourceCode的字符串变量。十、

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

我想匹配'100000000*10**'和'300000000*10**',它应该给我以下两行作为使用re的输出。芬德尔

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

目前我有以下代码:

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

错误地输出为:

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

任何帮助都将不胜感激。

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/129598
 
1389 次点击  
文章 [ 2 ]  |  最新文章 3 年前
Cubed
Reply   •   1 楼
Cubed    3 年前
pattern = '[0-9]0{4,}[0-9\s*]*'
matches = re.findall(pattern, strSourceCode, re.MULTILINE)

它与整条线不匹配。 该模式搜索后跟至少四个零的数字,然后再后跟任意数量的空格、数字和数字 * 角色。

如果你想精确匹配 * 10** 完成大数字后,您可以执行以下操作:

pattern = '[0-9]0{4,} \* 10\*\*'
matches = re.findall(pattern, strSourceCode, re.MULTILINE)
Tim Biegeleisen
Reply   •   2 楼
Tim Biegeleisen    3 年前

我们可以尝试使用 re.findall 在多行模式下:

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)

这张照片是:

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

这里使用的正则表达式模式试图找到任何包含整数乘以10的整数幂的行。