使用正则表达式检查字符串是否只包含一位数字

Using regex to check if a string contains only one digit

我正在编写一个算法,我需要检查一个字符串是否只包含 一个 数字(不超过一个)。目前我有:

if(current_Operation.matches("\d")){
...
}

有没有更好的方法来做到这一点?谢谢

使用正则表达式

/^\d$/

这将确保整个字符串包含一个数字。 ^匹配行首,$匹配行尾。

您可以使用:

^\D*\d\D*$
# match beginning of the line
# non digits - \D*
# one digit - \d
# non digits - \D*
# end of the line $

参见 a demo on regex101.com(为清楚起见添加了换行符)。

如果您不想使用正则表达式:

int numDigits = 0;
for (int i = 0; i < current_Operation.length() && numDigits < 2; ++i) {
  if (Character.isDigit(currentOperation.charAt(i))) {
    ++numDigits;
  }
}
return numDigits == 1;