如何确定一个字符串是否包含整数?

5

如果你有一个字符串,想要测试它是否包含整数,以便在继续进行其他代码之前进行检查。在Java中,你会使用什么来确定它是否是整数?


2
你的问题不够清晰。你想检查它是否包含整数还是它本身就是整数?例如abc123或者123456? - Ash Burlaczenko
@Ash 找出它是否为整数 - 对我来说,问题很清楚(标题不明确)。 - Andreas Dolk
您可能还想查看这个链接:https://dev59.com/j3A75IYBdhLWcg3wAUJ9 - CoolBeans
12个回答

15

如果你想确保一个字符串只包含整数并将其转换为整数,我建议使用 try/catch 中的parseInt方法。然而,如果你想检查字符串是否包含数字,则最好使用String.matches正则表达式stringVariable.matches("\\d")


8
您可以检查以下内容是否正确:"yourStringHere".matches("\\d+")。这将检查字符串中是否只包含数字。请注意保留HTML标记。

作为澄清,这将检查您的字符串是否与正则表达式“\d+”匹配,该表达式表示一个或多个数字[0-9]。 - Seabass77

5
String s = "abc123";
for(char c : s.toCharArray()) {
    if(Character.isDigit(c)) {
        return true;
    }
}
return false;

3
尝试使用 "for(char c : s.toCharArray())" 替代。 - cytinus

1
我使用String类中的matches()方法:
    Scanner input = new Scanner(System.in)
    String lectura;
    int number;
    lectura = input.next();
    if(lectura.matches("[0-3]")){
         number = lectura;
    }

这样您也可以验证数字范围是否正确。

1

0
  1. 用户正则表达式:

    Pattern.compile("^\\s*\\d+\\s*$").matcher(myString).find();

  2. 将 Integer.parse() 用 try/catch(NumberFormatException) 包装起来即可。


正则表达式能否将 ١ 识别为数字? - Michael Konietzka
对不起,我不认识这个字符。这是什么? - AlexR
这是阿拉伯-印度数字1。请自行尝试:System.out.println(Integer.valueOf("١")); - Michael Konietzka

0

0

你可以随时使用谷歌的Guava库

String text = "13567";
CharMatcher charMatcher = CharMatcher.DIGIT;
int output = charMatcher.countIn(text);

0

那应该可以运行:

public static boolean isInteger(String p_str)
{
    if (p_str == null)
        return false;
    else
        return p_str.matches("^\\d*$");
}

-1
int number = 0;
try { 
   number = Integer.parseInt(string); 
}
catch(NumberFormatException e) {}

欢迎来到stackoverflow。这个问题很旧,已经有答案了。通常情况下,最好不要重新激活过时的帖子,除非你的回复在之前的答案中提供了显著新的或不同的内容。 - oers

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接