【问题标题】:Is there a way to see if there is only numbers in a string? [duplicate]有没有办法查看字符串中是否只有数字? [复制]
【发布时间】:2014-07-29 22:12:19
【问题描述】:

我正在尝试对表单进行错误检查。我想通过它是否包含所有号码来查看电话号码是否有效。有没有办法查看一个字符串中是否只有 nmbers?

【问题讨论】:

  • 只是确保它不是 HTML 表单?无论哪种方式:当然有。一种方法是模式/正则表达式。你应该做你的研究。
  • 正则表达式是允许接受像“(385)-141-3423”这样的字符串的一种选择。
  • 取决于您是否可以添加示例接受的数字格式。
  • 假设您也不想检查模式。然后您可以在循环中检查每个数字/字符的 ASCII 值。 if(string.charAt(i) < 48 || string.charAt(i) > 58){//Not number}

标签: java


【解决方案1】:

您可以为此使用 regex

if(value.matches("[0-9]+")) {
    System.out.println("Only numbers!");
}

【讨论】:

  • ...所以你是说如果我提交一个数值,它会返回“只有数字!”??您的if 声明可能不正确。
【解决方案2】:

使用正则表达式验证电话号码的模式

"\\d{3}-\\d{7}"

例如:

 310-6666666

如果你只想从字符串中读取整数

public class Agent{
 public static void main(String...args){
    String input = "1 23 35 5d 8 0 f";
    List<Integer> intList = new ArrayList<Integer>();

Arrays.asList(input.split(" ")).stream().forEach( i -> {
        try{
          intList.add(Integer.parseInt(i));
        }catch(Exception ex){

        }
});

intList.forEach( i -> System.out.print(" " + i));

}

输出:

1 23 35 8 0

【讨论】:

    猜你喜欢
    • 2013-09-20
    • 1970-01-01
    • 2016-03-04
    • 2016-09-20
    • 2011-06-27
    • 2023-03-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多