【问题标题】:Using regex to check if a string contains only one digit使用正则表达式检查字符串是否仅包含一位数字
【发布时间】:2017-02-09 11:26:33
【问题描述】:

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

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

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

【问题讨论】:

  • 这种方式有什么问题?
  • 模式:^\D*\d\D*$.
  • 看来我用这种方式没有得到正确的结果。让我仔细检查一下
  • 如果一个字符串包含任何地方?我很想写if(str.length == 1 && isDigit(str[0])。来自std.asciiisDigit 足以进行基本检查。
  • 请注意,“d”标签用于D编程语言,请不要因为您的示例中恰好有“d”而使用它

标签: java regex string digit


【解决方案1】:

你可以使用:

^\\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(为清楚起见添加了换行符)。

【讨论】:

  • @Jan 在同一个正则表达式中,我们如何检查数字是否仅在 0-6 之间
【解决方案2】:

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

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】:

    使用正则表达式

    /^\d$/
    

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

    【讨论】:

    • 他要求检查字符串是否包含数字并且不仅仅是数字。但它应该只包含一个数字
    • @WebFreak001 是的,你是对的。字符串本身也包含括号,但我正在检查它是否只包含一位数字。
    猜你喜欢
    • 2012-02-19
    • 1970-01-01
    • 2022-12-28
    • 1970-01-01
    • 2014-03-30
    • 2017-05-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多