[英]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
以“ 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.