Using regex to check if a string contains only one digit

梦想的初衷 提交于 2020-12-12 05:10:50

问题


I'm writing an algorithm and I need to check if a string contains only one digit (no more than one). Currently I have:

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

Is there a better way to go about doing this? Thanks.


回答1:


You can use:

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

See a demo on regex101.com (added newlines for clarity).




回答2:


If you fancied not using a regular expression:

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



回答3:


Use the regular expression

/^\d$/

This will ensure the entire string contains a single digit. The ^ matches the beginning of the line, and the $ matches the end of the line.



来源:https://stackoverflow.com/questions/39799056/using-regex-to-check-if-a-string-contains-only-one-digit

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!