形成一个正则表达式解析表达式数值 [英] Forming a Regex to Parse Numerical Expressions

查看:114
本文介绍了形成一个正则表达式解析表达式数值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图解析字符串形式的数字比较。我要来标记一个字符串,如 45+(30 * 2)< = 50 使得产生的群体是 45 + (30 * 2)< = 50



我知道我可以定义我的组作为




  • \w * 的计数值

  • \(。* \)的括号条款

  • [\ \ + - \ *。\\ \\\ = LT;>] {1,2} 为运营商而言



但我不知道怎么说一个数字或长期括号后面的操作来看,那整个事情重复任意次数,以数字或括号长期结局。



时,这样的事情可能与正则表达式?


解决方案

一个正规表达是不完全适合工作的最佳工具。您的可以的达到你想要跟他们什么,但你必须赴汤蹈火。



第一个被嵌套的结构,如 45 +((10 + 20)* 2)≤(。* \)= 50 ,让我们开始了工作第一,为 \ 不会做你任何好处。它的渴望的和不知道嵌套结构的



下面是括号,只有更好的方式:



<?pre> (大于
(小于p> \()
|(小于3 -P> \))
|(?(p)[^()])(?(p)
)+
(?))

是的,这就是它需要。阅读关于均衡组了解这方面的一个深入的解释。



数值计算将由 \d + [0-9] + (ASCII码只在数字匹配。.NET),而不是由 \w +



至于你的问题:




一个数值或括号术语随后的操作的术语,并且重复任意次数的整个事情,在一个数值或括号术语结束




您正在试图做的是错的。当你的可能的做到这一点与PCRE正则表达式,它会在.NET更难。



您可以使用正则表达式的词法的(又名标记化的)。但后来使用的应用程序代码,以使正则表达式返回令牌感。不要使用正则表达式语法,你会不会用漂亮的代码而告终。



也许你应该使用现有的数学解析库,如的 NCalc



或者,你可能需要去同一个定制的解决方案和< A HREF =http://stackoverflow.com/a/29996191/3764814>建立你自己的解析器 ...


I am trying to parse numerical comparisons in string form. I want to tokenize a string such as 45+(30*2)<=50 such that the resulting groups are 45, +, (30 * 2), <=, and 50.

I know I can define my groups as

  • \w* for the numerical terms
  • \(.*\) for the parenthetical terms
  • [\+\-\*\\=<>]{1,2} for the operator terms

but I don't know how to say "A numerical or parenthetical term followed by an operational term, and that whole thing repeated any number of times, ending in a numerical or parenthetical term".

Is such a thing possible with regex?

解决方案

A regular expression isn't exactly the best tool for the job. You can achieve what you want with them, but you'll have to jump through hoops.

The first one being nested constructs like 45+((10 + 20)*2)<=50, so let's start working on that first, as \(.*\) won't do you any good. It's eager and unaware of nested constructs.

Here's a better pattern for parentheses only:

(?>
    (?<p>\()
    |(?<-p>\))
    |(?(p)[^()])
)+
(?(p)(?!))

Yes, that's what it takes. Read about balancing groups for an in-depth explanation of this.

Numerical terms would be matched by \d+ or [0-9]+ (for ASCII only digits in .NET), not by \w+.

As for your question:

A numerical or parenthetical term followed by an operational term, and that whole thing repeated any number of times, ending in a numerical or parenthetical term

You're trying to do it wrong. While you could do just that with PCRE regexes, it'll be much harder in .NET.

You can use regexes for lexing (aka tokenizing). But then use application code to make sense of the tokens the regex returns you. Don't use regex for semantics, you won't end up with pretty code.

Perhaps you should use an existing math parsing library, such as NCalc.

Or you may need to go with a custom solution and build your own parser...

这篇关于形成一个正则表达式解析表达式数值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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