且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

简单算术字符串的正则表达式

更新时间:2023-02-10 19:56:54

试试这个。这很丑陋但它应该有用(如果你没有使用任何括号):

Try this. It's ugly as hell but it should work (if you aren't using any parentheses):

-?\d+(?:\.\d+(?:E\d+)?)?(\s*[-+/\*]\s+-?\d+(?:\.\d+(?:E\d+)?)?)+

解释

这将算一个数字后跟一个运算符和一个数字无限期

This will math a number followed by an operator and a number indefinitely


  • - ?\\ \ +(?:\。\\\ +(?:E \ d +)?)?匹配一个数字



    • \ * * 可选空格

    • [ - + / \ *] 任何运算符: + - * /

    • \s + 至少一个空格(以避免--b)

    • - ?\d +(?:\ 。\ + +(?:E \ d +)?)?匹配另一个号码

    • -?\d+(?:\.\d+(?:E\d+)?)? Match a number
    • (
      • \s* optional whitespace
      • [-+/\*] any operator: +, -, *, /
      • \s+ at least one whitespace (to avoid a --b)
      • -?\d+(?:\.\d+(?:E\d+)?)? match another number

      数字表达式:


      • - ?可选 -

      • \d + 数字(一个或多个)

      • (?: start可选部分

        • \。 dot

        • \d + 数字

        • (?:可选科学记数法部分的开头

          • E匹配 E char

          • \d + 匹配digitx

          • -? optional -
          • \d+ digits (one or more)
          • (?: start of optional part
            • \. dot
            • \d+ digits
            • (?: start of optional scientific notation part
              • E match E char
              • \d+ match digitx

              但我强烈建议尝试为此编写一个合适的解析器,它还允许支持括号: a +(b + c)

              But i strongly suggest trying to write a proper parser for this, it will also allow supporting of parentheses: a + (b + c).