在Python中处理冗余的regex(sub)字符串

2024-04-26 06:38:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一组表达式,可能有很多冗余代码。你知道吗

例如:

(number) is larger than (number)

或者

(string) has exactly (integer) characters

我有很多这种类型的表达式,我可以复制粘贴正则表达式中的一个数[-+]?\d*\.\d+|\d+,但最终会导致大量的冗余代码。所以我想知道是否有一个方法(模块)可以让我在Python中更有效地完成这个任务?你知道吗

在最理想的情况下,参数将根据其类型进行处理。一个数字将被处理为浮点数,整数被处理为整数,依此类推。你知道吗

我可能认为regex不是正确的工具。你知道吗


Tags: 方法代码类型numberstringis表达式整数
1条回答
网友
1楼 · 发布于 2024-04-26 06:38:20

So I will have many times for example this string \d*\.\d+|\d+ because I want to match a float in most of these regexes. So I would be nicer to match them in other way. Because if I want to change the regex for a float, I have to search and replace them all.

您可以将模式(对于一个子串)或(对于一个完整的字符串更好)一次regular expression object赋给一个变量,例如numprog = re.compile(r'[-+]?\d*\.\d+|\d+'),并使用这个变量的match()search()方法多次进行匹配,例如result = numprog.match(string)。你知道吗

相关问题 更多 >