【问题标题】:Python regex for infix calculator用于中缀计算器的 Python 正则表达式
【发布时间】:2016-02-13 06:17:19
【问题描述】:

我需要一个正则表达式来捕捉...

( ) + - * /

以下两种格式的数字...

xxx.xxx

IE 3.14159

xxx

IE 42

我有……

re.findall('[+-/*//()]|\d+(\.\d+)?', noWhitespaces)

下面的表达式...

(2.0 + 2.0) / 1

...正在生成...

['', '.0', '', '.0', '', '', '']

我不知道为什么。

我有...

re.findall('[+-/*//()]|\d+\.\d+', noWhitespaces)

适用于 xxx.xxx 格式的数字 IE 2.0 和运算符,但不适用于 xxx 格式的数字,即 1

编辑:确切的代码...

noWhitespaces = re.sub(r'\s+', '', s)
print(noWhitespaces)
tokens = re.findall(r'[-+/*//()]|\d+(\.\d+)?', noWhitespaces)
print(tokens)

【问题讨论】:

标签: python regex


【解决方案1】:

只需将\d+\.\d+ 中的第二个点部分设为可选即可。

>>> import re
>>> s = '(2.0 + 2.0) / 1'
>>> re.findall(r'[-+/*()]|\d+(?:\.\d+)?', s)
['(', '2.0', '+', '2.0', ')', '/', '1']

请注意,您需要将捕获组设置为非捕获组,因为findall 应该优先考虑捕获。这就是为什么你在输出中得到.0 的原因,即捕获组捕获的字符串。

【讨论】:

  • 我添加了其他正则表达式代码。它真的不适合我
  • 将捕获组设为非捕获组。
猜你喜欢
  • 2020-04-22
  • 2016-02-13
  • 1970-01-01
  • 2012-11-30
  • 1970-01-01
  • 1970-01-01
  • 2013-03-13
  • 1970-01-01
相关资源
最近更新 更多