Python正则表达式在文本字符串中查找算术表达式 [英] Python regex to find arithmetic expressions in text strings

查看:73
本文介绍了Python正则表达式在文本字符串中查找算术表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试在文本字符串中找到算术表达式.

I try to find arithmetic expressions in text strings.

可能的算术表达式:

1/3 + 1/4
cos(30) + 25*3,75
sqrt(5) + sin(45)
5 != 6
2**4 + 100.000 =
(2^3)^4
sqrt((0,25*8)/2)
3e4 - 500

1/3 + 1/4
cos(30) + 25*3,75
sqrt(5) + sin(45)
5 != 6
2**4 + 100.000 =
(2^3)^4
sqrt((0,25*8)/2)
3e4 - 500

我创建了一个正则表达式,并在块之间使用了|符号.

I created a regex and used the | symbol between the blocks.

pattern = '((\s*(sqrt|a?sin|a?cos|a?tan|abs|log|log10|exp)?\s*)* | (\s*[e0-9,.()\-]+\s*)* | (\spi\s*)* | (\s*[-+*/%^<>!=]*\s*)*)(\s*\=?\s*)?'

我真正想要的是所有块都可以按任何顺序互换使用.

What I really want is that all blocks can be used interchangeably in any order.

我该怎么做?使用|符号不起作用.

How can I do that? It doesn't work using | symbol.

推荐答案

使用递归正则表达式的示例

An example using recursive regex

([\d,.e]+|(cos|sin|sqrt)\((?R)\)|\([ ]*(?R)[ ]*\))([ ]*[-+*\/!=^]+[ ]*(?R))*

可以进行改进以更加严格地匹配运算符或数字

Could be improved to be more strict to match operators or numbers

  • (?R)递归引用整个正则表达式
  • (?R) refering recursively the whole regex

这篇关于Python正则表达式在文本字符串中查找算术表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆