簡體   English   中英

正則表達式匹配數字和運算符之間的空格,但數字之間沒有空格

[英]Regular Expression to match spaces between numbers and operators but no spaces between numbers

我在這個論壇上搜索了很多帖子,令我驚訝的是,我還沒有找到任何像我這樣的問題的人。 我必須為控制台中的字符串值制作一個簡單的計算器。 現在,我正在嘗試制作一些正則表達式來驗證輸入。 我的計算器必須接受在運算符之間帶有空格的數字(僅允許使用+和-),但不能接受在數字之間帶有空格的數字,以進行總結:2 + 2 = 4是正確的,但是2 2 + 2->這應該犯一個錯誤,並在控制台上通知用戶他在數字之間放置空格。

我想出了這個:

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=24或6-4 6 - 4 = 2 ,一個正則表達式像

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

會做。 查看示例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+$

請看示例2

嘗試:

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

演示版

說明:

  • ^$錨定正則表達式以匹配整個字符串
  • 我添加了\\s*以允許每個數字/運算符之間的空格。
  • 我用\\d替換了[0-9]只是為了稍微簡化一下; 兩者是等效的。

我不清楚您是否要在最后允許/禁止包含= <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");

示例工作版本在這里


說明

下面允許可替換的空格。

\\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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM