我在這個論壇上搜索了很多帖子,令我驚訝的是,我還沒有發現任何人有像我這樣的問題。 我必須爲控制檯的字符串值做一個簡單的計算器。現在,我試圖做一些正則表達式來驗證輸入。 我的計算器必須接受操作符之間有空格的數字(只允許+和 - 是允許的),但不包括數字之間有空格的數字,總結如下: 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");
你能不能給我一個大概的正則表達式我應該用暗示?
你沒有找到答案的原因可能是因爲正則表達式不是確定字符串是否是有效的數學方程的好工具!當您開始添加其他運算符(如括號,指數等)時會發生什麼? –
...但是,如果我們將問題限制爲您提到的簡單類型的方程,那麼當然可以用正則表達式來完成。 –
使用下面的正則表達式 \ d * \ s \ + \ s \ d * \ s –