正则表达式匹配数字和运算符之间的空格但数字之间没有空格

Regular Expression to match spaces between numbers and operators but no spaces between numbers

我在这个论坛上搜索了很多 post ,令我惊讶的是,我没有找到任何人遇到像我这样的问题。 我必须为来自控制台的字符串值制作一个简单的计算器。现在,我正在尝试制作一些正则表达式来验证输入。 我的计算器必须接受运算符之间带有 spaces 的数字(仅允许 + 和 - ),但不能接受数字之间带有 spaces 的数字,总结一下: 2 + 2 = 4 是正确的,但是 2 2 + 2 --> 这应该会出错并在控制台上通知用户他将 space 放在数字之间。

我想到了这个:

static String properExpression = "([0-9]+[+-]?)*[0-9]+$";
static String noInput = ""; 
static String numbersFollowedBySpace = "[0-9]+[\s]+[0-9]";
static String numbersWithSpaces = "\d+[+-]\d+"; 

//I've tried also "[\d\s+\d]";

void validateUserInput() {
Scanner sc = new Scanner(System.in);
System.out.println("Enter a calculation.");
input = sc.nextLine();

if(input.matches(properExpression)) {
calculator.calculate();

} else if(input.matches(noInput)) {
    System.out.print(0);

} else if(input.matches(numbersFollowedBySpace)) {
    input.replaceAll(" ", "");
    calculator.calculate();

    } else if(input.matches(numbersWithSpaces)) 
       {
          System.out.println("Check the numbers. 
It seems that there is a space between the digits");
        } 

   else System.out.println("sth else");

你能给我一些关于我应该使用的正则表达式的提示吗?

要匹配一个完整的表达式,如2+3=246 - 4 = 2,正则表达式如

^\d+\s*[+-]\s*\d+\s*=\s*\d+$

会的。查看example 1哪里可以玩。

如果你想匹配更长的表达式,比如 2+3+4+5=14 那么你可以使用:

^\d+\s*([+-]\s*\d+\s*)+=\s*\d+$

解释:

^\d+                   # first operand
\s*                    # 0 or more spaces
(                      # start repeating group
 [+-]\s*               # the operator (+/-) followed by 0 or more spaces
 \d+\s*                # 2nd (3rd,4th) operand followed by 0 or more spaces
)+                     # end repeating group. Repeat 1 or more times.
=\s*\d+$               # equal sign, followed by 0 or more spaces and result.

现在,您可能想要接受像 2=2 这样的表达式作为有效表达式。在那种情况下,重复组可能不存在,因此将 + 更改为 *:

^\d+\s*([+-]\s*\d+\s*)*=\s*\d+$

看看 example 2 那个。

尝试:

^(?:\d+\s*[+-])*\s*\d+$

Demo

解释:

  • ^$ 锚定正则表达式以匹配 整个字符串
  • 我添加了 \s* 以允许每个 number/operator 之间有空格。
  • 我将 [0-9] 替换为 \d 只是为了稍微简化一下;两者是等价的

我有点不清楚你是否想 allow/disallow 包括最后的 = <digits>,因为你的问题提到了这一点,但你尝试的 properExpression 表达式并没有尝试它。如果是这种情况,应该很容易看出如何修改表达式以支持它。

请注意,除了正则表达式问题之外,我没有尝试解决由任何其他问题引起的任何潜在问题。 尽可能地保持你的逻辑流程。虽然还有其他更有效的答案,但你必须改变你的逻辑流程很多。

请看下面,如果您有任何问题,请告诉我。

static String properExpression = "\s*(\d+\s*[+-]\s*)*\d+\s*";
static String noInput = ""; 
static String numbersWithSpaces = ".*\d[\s]+\d.*"; 
//I've tried also "[\d\s+\d]";

static void validateUserInput() {
  Scanner sc = new Scanner(System.in);
  System.out.println("Enter a calculation.");
  String input = sc.nextLine();

  if(input.matches(properExpression)) {
      input=input.replaceAll(" ", "");  //You've to assign it back to input.
      calculator.calculate();           //Hope you have a way to pass input to calculator object
  } else if(input.matches(noInput)) {
      System.out.print(0);
  } else if(input.matches(numbersWithSpaces)) {
            System.out.println("Check the numbers. It seems that there is a space between the digits");
  } else 
    System.out.println("sth else");

样本工作版本here


说明

下面允许替换空格..

\s*     //Allow any optional leading spaces if any
(        //Start number+operator sequence
\d+     //Number
\s*     //Optional space
[+-]     //Operator
\s*     //Optional space after operator
)*       //End number+operator sequence(repeated)
\d+     //Last number in expression
\s*     //Allow any optional space.

带空格的数字

.*         //Any beginning expression
\d        //Digit
[\s]+     //Followed by one or more spaces
\d        //Followed by another digit
.*         //Rest of the expression