正则表达式允许数学运算

2024-04-26 01:12:44 发布

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

这是我目前拥有的正则表达式(不起作用)

^(pow|sqrt|[0-9*,/\-\+\(\)])+$

我只想允许以下字符:+-/,*(),数字0-9和这些单词powsqrt。 它基本上只允许基本的数学运算和pow(x,x)sqrt(x),其中x是一个数字。你知道吗

示例:

2+2 should pass

pow(3,2) should pass

abs(3.33) should fail 3*2+3 -(10/2) should pass


Tags: 示例数字数学passabssqrt字符单词
3条回答

虽然这并不能直接回答OP的问题。我觉得这些都是必读的,特别是在处理用户输入时。你知道吗

  • SANDBOX ESCAPE
    This is the traditional rationale against using eval(). You cannot simply let the user to run arbitrary code on the server, as they could simply do import os ; os.remove(“/home”).
  • CPU BURNING ATTACK
    If you let the user to input arbitrary calculations, they can try to make the calculations so complex that your process keeps calculating the math expression forever, mounting a denial of service attack against the service.
  • MEMORY BURNING ATTACK
    Memory burning attack is similar to CPU burning attack. Instead of CPU cycles, the attacker tries to run make the process run out of memory. One could input a very long math expression. Alternatively, the power operation could be used to create very large numbers not fitting to the process memory.

阅读更多信息:https://opensourcehacker.com/2014/10/29/safe-evaluation-of-math-expressions-in-pure-python/


为了为用户交互提供类似eval的safish方法,我可以找到两个库:

但这些可能相当沉重和复杂。因此,除此之外,还可以使用PLY编写一个简单解析器,并将输入提供给解析器。下面是一个使用PLY:https://github.com/dabeaz/ply/blob/master/example/calc/calc.py制作计算器的完整示例

因为PLY是纯python。这应该相对容易。你知道吗

我发现了两个错误,您也应该转义/,并且您忘记了数字0。但这在不同的regex实现中可能有所不同。你知道吗

^(pow|sqrt|[0-9*,\/\-\+\(\)])+$

当然,这个正则表达式并不能确保句子是有效的数学运算,例如:powpow12/*-12将被接受。Regex不是解析数学表达式的合适工具。你知道吗

https://regex101.com/r/cI6oM2/1

您有一些语法问题:

^(pow|sqrt|[0-9\*\,/\-\+\(\)])+$

应该有用。 但它不考虑字符顺序,“pow9(10,sqrt)”将是正确的,您不能用regex执行此操作。你知道吗

相关问题 更多 >

    热门问题