【问题标题】:Split in Regex Python Infix Notation in Numerical Expressions在数值表达式中拆分正则表达式 Python 中缀表示法
【发布时间】:2022-01-25 17:04:54
【问题描述】:

我想编写一个 Python 脚本,用户可以这样输入:

input1 = "12/(2+4)*21**2"
input2 = "12,/,(,2,+,4,),*,21,**,2"
input3 = "12 / ( 2 + 4 ) * 21 ** 2"

输出应该总是这样:

output = ["12", "/", "(", "2", "+", "4", ")", "*", "21", "**", "2"]
  

我一直在做的是:

re.sub("([/+*](**))", r" \1 ", expression).split()

但它不起作用,我对正则表达式不是很熟悉。有人可以帮忙吗?

【问题讨论】:

  • 您的问题需要更详细地说明您想要实现的具体目标。你能用正则表达式写出你想强制执行的规则吗?

标签: python regex


【解决方案1】:

如何使用替代:

>>> re.findall(r"\d+|\*+|[-+/()]", input1)
['12', '/', '(', '2', '+', '4', ')', '*', '21', '**', '2']
>>> re.findall(r"\d+|\*+|[-+/()]", input2)
['12', '/', '(', '2', '+', '4', ')', '*', '21', '**', '2']
>>> re.findall(r"\d+|\*+|[-+/()]", input3)
['12', '/', '(', '2', '+', '4', ')', '*', '21', '**', '2']

【讨论】:

  • 考虑到不会要求您检查字符串的数学正确性(例如,[ "(", "1", "2", "("])将为"(1 2(" 返回),您可以将[-+/()] 替换为[^, ]。跨度>
猜你喜欢
  • 2021-10-07
  • 1970-01-01
  • 2015-10-01
  • 2014-10-27
  • 1970-01-01
  • 2012-04-20
  • 1970-01-01
  • 2015-05-02
  • 1970-01-01
相关资源
最近更新 更多