簡體   English   中英

Java正則表達式匹配用戶輸入中的整數

[英]Java regular expression to match integers from user input

我試圖提高我的正則表達式技能,所以我做了一個基本的計算器來練習模式匹配。 提示用戶在控制台中輸入兩個整數值,中間用逗號隔開,中間不能有空格。 我不擔心值太大而無法處理int,我只想涵蓋用戶輸入-0的情況。 正0,所有其他負和正值都應接受。

掃描程序對象從用戶那里獲取輸入,並將其存儲在字符串變量中。 然后將此變量傳遞給具有Pattern and Matcher的方法,該方法進行匹配並返回是否匹配的布爾值。

String userInput = scanner.next();

//look for only integers, especially excluding -0
if(checkUserMathInputIsGood("REGEX", userInput))
    {
        int sum;
        String[] twoNumbersToAdd = userInput.split(",");

        sum = Integer.parseInt(twoNumbersToAdd[0]) + Integer.parseInt(twoNumbersToAdd[1]);

        System.out.println(sum);
    }

在經過數小時的搜索stackoverflow,javadocs等之后,我發現了一些幾乎可以解決的解決方案。

http://www.vogella.com/tutorials/JavaRegularExpressions/article.html#regex_negative

http://www.regexplanet.com/advanced/java/index.html

Java正則表達式是否為負數?

以“ T(blah blah)”開頭的模式示例根本沒有用,而且我找不到對T應該完成的功能的引用。 我已經接近:

"-{0,1}(?!0)\\d+,-{0,1}(?!0)\\d+"

分解它,似乎是在說:允許減號最少0次,最多1次。 如果負號的所謂“負超前”為true,則不允許為0。 然后允許任何整數值至少為一個整數長。 但是,這導致正則表達式拒絕0以及-0。

應接受的輸入示例:
2,3
22,-4
-555,-9
0,88
0,0

應拒絕的輸入示例:
-0,9
432,-0
-0,-0

任何幫助或建議,我們將不勝感激。

如果我正確理解了要求,那么它應該是"-?\\\\d+,-?\\\\d+"

^(?:(?:\+?\d+)|(?:-(?!0*,)\d+)),(?:(?:\+?\d+)|(?:-(?!0*$)\d+))$

演示

說明:

^// match start of line or text
(?:// match either:
    (?:// option 1:
        \+? // a "+" if possible
        \d+ // and any number of digits
    )
    |// or
    (?:// option 2:
        - // a "-" sign
        (?!//negative lookahead assertion: do NOT match if next is...
            0*,//...any number of zeroes and a comma
        )
        \d+//if we've made it this far, then we know this integer is NOT zero. Match any number of digits.
    )
)
,// a comma.
(?:// this pattern is basically the same as the one for the first number.
    (?:
        \+?
        \d+
    )
    |
    (?:
        -
        (?!
            0*$// except this matches the end of a line or text instead of a comma.
        )
        \d+
    )
)
$// end of line or text.

暫無
暫無

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

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