需要仅接受%符号作为输入字符串

时间:2011-11-02 12:20:41

标签: java regex

我想只接受%符号(可选)作为带数字的字符串变量,如输入中的百分比。 E.G,1000%或100%或2000%或普通字符串输入为1000或2000。

我们可以借助正则表达式来完成吗?或者其他一些验证。

请帮忙

5 个答案:

答案 0 :(得分:2)

^[0-9]+%?$

假设至少需要一个数字,并且只允许正数(或0)。

如果你还想允许小数(你可以在你的问题中提到过),试试

^[0-9]+(?:\.[0-9]+)?%?$

这允许任何正整数或小数(但不是缩写形式,如.11.)。当然不支持指数表示法。

答案 1 :(得分:0)

您可以尝试使用数字和%作为可选字符。

^\d+(\.\d+)?%?$

答案 2 :(得分:0)

绝对。听起来你也想在这里消毒,所以“[0-9] {1,}%”或“[0-9] *。?[0-9] {1,}%”确保你匹配小数百分比。

通常我可能会说,jfgi但这太多了(好玩。编辑)

http://www.regular-expressions.info/reference.html

你可以使用正则表达式之外的东西来做,但这只是一个循环,断言输入的每个字符都是十进制数字,句点或百分号,并且它们是以适当的顺序。

希望这有帮助!

答案 3 :(得分:0)

尝试以下正则表达式

^[+-]?\d+(\.\d+)?%?$

应该使用小数

答案 4 :(得分:0)

基于此评论:

  

它似乎与1000%,100但现在的模式完美配合   小数值的问题,如101.50或199.50%

^[-+]?\d*\.?\d+\b%?$

说明:

"
^        # Assert position at the beginning of the string
[-+]     # Match a single character present in the list “-+”
   ?        # Between zero and one times, as many times as possible, giving back as needed (greedy)
[0-9]    # Match a single character in the range between “0” and “9”
   *        # Between zero and unlimited times, as many times as possible, giving back as needed (greedy)
\.       # Match the character “.” literally
   ?        # Between zero and one times, as many times as possible, giving back as needed (greedy)
[0-9]    # Match a single character in the range between “0” and “9”
   +        # Between one and unlimited times, as many times as possible, giving back as needed (greedy)
\b       # Assert position at a word boundary
%        # Match the character “%” literally
   ?        # Between zero and one times, as many times as possible, giving back as needed (greedy)
\$        # Assert position at the end of the string (or before the line break at the end of the string, if any)
"

作为旁注:你应该真的能够从@Tim的回答中考虑可选部分。看看其他答案提出的教程。