简体   繁体   English

正则表达式验证前缀,中缀和后缀表达式

[英]Regular Expressions to validade Prefix, Infix and Postfix expressions

I need to create a program in C# that converts an Infix expression into Prefix and Postfix, Prefix expression into Postfix and Infix, Postfix expression into Infix and Prefix. 我需要在C#中创建一个程序,将一个Infix表达式转换为Prefix和Postfix,将Prefix表达式转换为Postfix和Infix,将Postfix表达式转换为Infix和Prefix。 This is not the problem though, the "processing part" of the program is already done. 但这不是问题,程序的“处理部分”已经完成。

What I need now is a regular expression to verify if the user input is an Infix, Prefix or Postfix expression, so depending on the input I call a different function to perform the conversions. 我现在需要的是一个正则表达式来验证用户输入是否是Infix,Prefix或Postfix表达式,因此根据输入我调用另一个函数来执行转换。

The input will always be: 输入将始终是:
For operands: capital single letters from A to Z 对于操作数:从A到Z的大写单字母
For operators: +, -, * and / 对于运营商:+, - ,*和/

For the Infix expression I made this regular expression (which seems to be working fine): 对于Infix表达式,我创建了这个正则表达式(似乎工作正常):
"^(([AZ])(([+]|[-]|[*]|[/])([AZ]))*)$"

But I extinguished my ideas trying to make a regular expression for Prefix and Postfix expressions. 但是我试图为Prefix和Postfix表达式制作一个正则表达式,从而熄灭了我的想法。 I also found nothing on internet. 我也没有在网上找到任何东西。

Could someone give me a light? 有人可以给我一个灯吗?

Unfortunately this isn't possible without recursive regex (which C# doesn't support). 不幸的是,如果没有递归正则表达式(C#不支持),这是不可能的。 While (well-formed) infix notation can be matched with the simple regex [AZ](?:[*/+-][AZ])* , pre- and postfix notation don't follow such a simple pattern that they could be matched by non-recursive regex. 虽然(格式良好的)中缀符号可以与简单的正则表达式[AZ](?:[*/+-][AZ])*匹配,但前缀和后缀符号不会遵循这样一个简单的模式,它们可能是与非递归正则表达式匹配。

That said, a very simple way to determine if an expression uses pre-/postfix notation (without verifying its correctness) is to check whether the first/last character is an operator: ^[*/+-] would match a well-formed prefix expression and .*[*/+-]$ a well-formed postfix expression. 也就是说,确定表达式是否使用前/后符号(不验证其正确性)的一种非常简单的方法是检查第一个/最后一个字符是否为运算符: ^[*/+-]将匹配格式良好前缀表达式和.*[*/+-]$一个格式正确的后缀表达式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM