可能使用正则表达式验证中缀表示法

发布于 2024-11-03 08:25:13 字数 133 浏览 1 评论 0原文

我正在考虑验证由字母作为操作数和 +-*/$ 作为运算符组成的中缀表示法 [例如:A+B-(C/D)$(E+F)] 在 Java 中使用正则表达式。还有更好的办法吗?有我可以使用的正则表达式模式吗?

I am thinking of validating an infix notation which consists of alphabets as operands and +-*/$ as operators [eg: A+B-(C/D)$(E+F)] using regex in Java. Is there any better way? Is there any regex pattern which I can use?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

智商已欠费 2024-11-10 08:25:14

我不熟悉 infix 的语言语法,但是您当然可以进行首次通过验证检查,它只是验证字符串中的所有字符是否有效(即可接受的字符 = AZ+-*/$)。这是一个检查有效字符的 Java 程序,还包含一个检查不平衡(可能嵌套)括号的函数:

import java.util.regex.*;
public class TEST {
    public static void main(String[] args) {
        String s = "A+B-(C/D)$(E+F)";
        Pattern regex = Pattern.compile(
            "# Verify that a string contains only specified characters.\n" +
            "^                # Anchor to start of string\n" +
            "[A-Z+\\-*/$()]+  # Match one or more valid characters\n" +
            "$                # Anchor to end of string\n",
            Pattern.COMMENTS);
        Matcher m = regex.matcher(s);
        if (m.find()) {
            System.out.print("OK: String has only valid characters.\n");
        } else {
            System.out.print("ERROR: String has invalid characters.\n");
        }
        // Verify the string contains only balanced parentheses.
        if (checkParens(s)) {
            System.out.print("OK: String has no unbalanced parentheses.\n");
        } else {
            System.out.print("ERROR: String has unbalanced parentheses.\n");
        }
    }
    // Function checks is string contains any unbalanced parentheses.
    public static Boolean checkParens(String s) {
        Pattern regex = Pattern.compile("\\(([^()]*)\\)");
        Matcher m = regex.matcher(s);
        // Loop removes matching nested parentheses from inside out.
        while (m.find()) {
            s = m.replaceFirst(m.group(1));
            m.reset(s);
        }
        regex = Pattern.compile("[()]");
        m = regex.matcher(s);
        // Check if there are any erroneous parentheses left over.
        if (m.find()) {
            return false;   // String has unbalanced parens.
        }
        return true;        // String has balanced parens.
    }
}

这​​不会验证语法,但作为过滤掉明显错误字符串的第一个测试可能很有用。

I am not familiar with the language syntax of infix, but you can certainly do a first pass validation check which simply verifies that all of the characters in the string are valid (i.e. acceptable characters = A-Z, +, -, *, /, $, ( and )). Here is a Java program which checks for valid characters and also includes a function which checks for unbalanced (possibly nested) parentheses:

import java.util.regex.*;
public class TEST {
    public static void main(String[] args) {
        String s = "A+B-(C/D)$(E+F)";
        Pattern regex = Pattern.compile(
            "# Verify that a string contains only specified characters.\n" +
            "^                # Anchor to start of string\n" +
            "[A-Z+\\-*/$()]+  # Match one or more valid characters\n" +
            "$                # Anchor to end of string\n",
            Pattern.COMMENTS);
        Matcher m = regex.matcher(s);
        if (m.find()) {
            System.out.print("OK: String has only valid characters.\n");
        } else {
            System.out.print("ERROR: String has invalid characters.\n");
        }
        // Verify the string contains only balanced parentheses.
        if (checkParens(s)) {
            System.out.print("OK: String has no unbalanced parentheses.\n");
        } else {
            System.out.print("ERROR: String has unbalanced parentheses.\n");
        }
    }
    // Function checks is string contains any unbalanced parentheses.
    public static Boolean checkParens(String s) {
        Pattern regex = Pattern.compile("\\(([^()]*)\\)");
        Matcher m = regex.matcher(s);
        // Loop removes matching nested parentheses from inside out.
        while (m.find()) {
            s = m.replaceFirst(m.group(1));
            m.reset(s);
        }
        regex = Pattern.compile("[()]");
        m = regex.matcher(s);
        // Check if there are any erroneous parentheses left over.
        if (m.find()) {
            return false;   // String has unbalanced parens.
        }
        return true;        // String has balanced parens.
    }
}

This does not validate the grammar, but may be useful as a first test to filter out obviously bad strings.

各空 2024-11-10 08:25:14

可能有点过头了,但您可以考虑使用成熟的解析器生成器,例如 ANTLR (http://www.antlr.org/)。使用 ANTLR,您可以创建规则来自动生成 java 代码。假设您在输入中仅获得有效字符,这是一个语法分析问题,否则您需要首先使用词法分析来验证字符流。

对于语法分析,您可能有这样的规则:

PLUS : '+' ;
etc...

expression:
         term ( ( PLUS | MINUS | MULTIPLY | DIVIDE )^ term )*
      ;
term:
    constant
  | OPENPAREN! expression CLOSEPAREN!
  ;

常量是整数/实数。如果 ANTLR 生成的解析器代码无法将输入与解析器规则相匹配,它将抛出异常,以便您可以确定代码是否有效。

Possibly overkill, but you might consider using a fully fledged parser generator such as ANTLR (http://www.antlr.org/). With ANTLR you can create rules that will generate the java code for you automatically. Assuming you have only got valid characters in the input this is a syntax analysis problem, otherwise you would want to validate the character stream with lexical analysis first.

For syntax analysis you might have rules like:

PLUS : '+' ;
etc...

expression:
         term ( ( PLUS | MINUS | MULTIPLY | DIVIDE )^ term )*
      ;
term:
    constant
  | OPENPAREN! expression CLOSEPAREN!
  ;

With constant being integers/reals whatever. If the ANTLR generated parser code can't match the input with your parser rules it will throw an exception so you can determine whether code is valid.

若有似无的小暗淡 2024-11-10 08:25:14

你也许可以用递归PCRE来做到这一点..但这可能是一个PITA。

由于您只想验证它,因此可以非常简单。只需使用堆栈,将所有元素一一压入并删除有效表达式。

定义一些规则,例如:

  • 仅当堆栈顶部有字母时才允许使用运算符
  • 仅当堆栈顶部有运算符时才允许使用字母或括号 如果
  • 堆栈为空,则所有内容都允许

  • 如果如果遇到右括号,请删除左括号之前的所有内容。
  • 如果遇到字母表,请

在每次删除表达式后删除该表达式,然后添加一个虚拟字母表。重复前面的步骤。
如果结果是字母表,则表达式有效。

或者类似的东西..

You probably could do it with recursive PCRE..but this may be a PITA.

since you only want to validate it, you can do it very simple. just use a stack, push all the elements one by one and remove valid expressions.

define some rules, for example:

  • an operator is only allowed if there is an alphabet on top of the stack
  • an alphabet or parentheses are only allowed if there is an operator on top of the stack
  • everything is allowed if the stack is empty

then:

  • if you encounter a closing parenthes remove everything up to the opening parenthes.
  • if you encounter an alphabet, remove the expression

after every removal of an expression, add an dummy alphabet. repeat the previous steps.
if the result is an alphabet, the expression is valid.

or something like that..

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文