在python中使用regex检查表达式是否有效

2024-06-26 14:30:19 发布

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

我正在检查字符串是否是有效的数学表达式。允许的操作为+、-、*、/和^。我试过了,不知道为什么不起作用:

a = raw_input("Unesite izraz")
if len( re.findall(r'(\d+(?:.\d+)?(?: [\+\-\/\*\^]\d+(?:.\d+) )* )', a ) ) != 0:

但对于有效表达式,此正则表达式返回[]。为什么?谢谢!在


Tags: 字符串reinputrawlenif表达式数学
3条回答

你的空间放错地方了。在

# yours / fixed
r'(\d+(?:.\d+)?(?: [\+\-\/\*\^]\d+(?:.\d+) )* )'
r'(\d+(?:.\d+)?(?: [\+\-\/\*\^] \d+(?:.\d+) )*)'

你可以在pythex.org试试

简单符号数学表达式的验证器可以是这样的。
这将是整个字符串的1次匹配。在

^\s*[+-]?\s*(?:\d+(?:\.\d*)?|\.\d+)(?:\s*[-+/*^]\s*\s*[+-]?\s*(?:\d+(?:\.\d*)?|\.\d+))*\s*$

格式:

 ^                             # BOS
 \s* [+-]? \s*                 # whitespace (opt), sign (opt), whitespace (opt)
 (?:                           # Integer or decimal
      \d+ 
      (?: \. \d* )?
   |  \. \d+ 
 )
 (?:                           # Cluster group
      \s* [-+/*^] \s*               # whitespace (opt), operation symbol (req'd), whitespace (opt)
      \s* [+-]? \s*                 # whitespace (opt), sign (opt), whitespace (opt)
      (?:                           # Integer or decimal
           \d+ 
           (?: \. \d* )?
        |  \. \d+ 
      )
 )*                            # End cluster, do 0 to many times
 \s*                           # optional whitespace
 $                             # EOS

您可以简化regexp。在

有一个运算符“except”:[^abc] 因此,它将采取任何不是字符“a”、“b”或“c”。在

import re

e1 = '1 + 2' # correct
e2 = '1 + 3 * 3 / 6 ^ 2' # correct
e3 = '1 + 3 x 3' # wrong

el = [e1, e2, e3]
regexp = re.compile(r'[^+\-*\/^0-9\s]')
for i in el:
    if len(regexp.findall(i)):
        print(i, 'wrong')
    else:
        print(i, 'correct')

您可以使用此站点来学习和测试您的regexp:https://regex101.com/

相关问题 更多 >