检查字符串是否包含数字 Java

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18590901/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 09:18:42  来源:igfitidea点击:

Check if a String contains numbers Java

javaregexstring

提问by Duane

I'm writing a program where the user enters a String in the following format:

我正在编写一个程序,用户在其中输入以下格式的字符串:

"What is the square of 10?"
  1. I need to check that there is a number in the String
  2. and then extract just the number.
  3. If i use .contains("\\d+")or .contains("[0-9]+"), the program can't find a number in the String, no matter what the input is, but .matches("\\d+")will only work when there is only numbers.
  1. 我需要检查字符串中是否有数字
  2. 然后只提取数字。
  3. 如果我使用.contains("\\d+")or .contains("[0-9]+"),无论输入是什么,程序都无法在字符串中找到数字,但.matches("\\d+")只有在只有数字时才能工作。

What can I use as a solution for finding and extracting?

我可以使用什么作为查找和提取的解决方案?

采纳答案by Duane

The solution I went with looks like this:

我采用的解决方案如下所示:

Pattern numberPat = Pattern.compile("\d+");
Matcher matcher1 = numberPat.matcher(line);

Pattern stringPat = Pattern.compile("What is the square of", Pattern.CASE_INSENSITIVE);
Matcher matcher2 = stringPat.matcher(line);

if (matcher1.find() && matcher2.find())
{
    int number = Integer.parseInt(matcher1.group());                    
    pw.println(number + " squared = " + (number * number));
}

I'm sure it's not a perfect solution, but it suited my needs. Thank you all for the help. :)

我确信这不是一个完美的解决方案,但它适合我的需求。谢谢大家的帮助。:)

回答by Konstantin Yovkov

Try the following pattern:

尝试以下模式:

.matches("[a-zA-Z ]*\d+.*")

回答by Evgeniy Dorofeev

try this

尝试这个

str.matches(".*\d.*");

回答by Reddy

Pattern p = Pattern.compile("(([A-Z].*[0-9])");
Matcher m = p.matcher("TEST 123");
boolean b = m.find();
System.out.println(b);

回答by Ruchira Gayan Ranaweera

You can try this

你可以试试这个

String text = "ddd123.0114cc";
    String numOnly = text.replaceAll("\p{Alpha}","");
    try {
        double numVal = Double.valueOf(numOnly);
        System.out.println(text +" contains numbers");
    } catch (NumberFormatException e){
        System.out.println(text+" not contains numbers");
    }     

回答by Thorsten Kettner

As you don't only want to look for a number but also extract it, you should write a small function doing that for you. Go letter by letter till you spot a digit. Ah, just found the necessary code for you on stackoverflow: find integer in string. Look at the accepted answer.

由于您不仅要查找数字而且还要提取它,因此您应该为您编写一个小函数。一个字母一个字母,直到你发现一个数字。啊,刚刚在 stackoverflow 上为您找到了必要的代码:find integer in string。查看已接受的答案。

回答by Melih Alt?nta?

I think it is faster than regex .

我认为它比 regex 快。

public final boolean containsDigit(String s) {
    boolean containsDigit = false;

    if (s != null && !s.isEmpty()) {
        for (char c : s.toCharArray()) {
            if (containsDigit = Character.isDigit(c)) {
                break;
            }
        }
    }

    return containsDigit;
}

回答by Sajal Dutta

If you want to extract the first number out of the input string, you can do-

如果你想从输入字符串中提取第一个数字,你可以这样做 -

public static String extractNumber(final String str) {                

    if(str == null || str.isEmpty()) return "";

    StringBuilder sb = new StringBuilder();
    boolean found = false;
    for(char c : str.toCharArray()){
        if(Character.isDigit(c)){
            sb.append(c);
            found = true;
        } else if(found){
            // If we already found a digit before and this char is not a digit, stop looping
            break;                
        }
    }

    return sb.toString();
}

Examples:

例子:

For input "123abc", the method above will return 123.

For "abc1000def", 1000.

For "555abc45", 555.

For "abc", will return an empty string.

对于输入“123abc”,上述方法将返回 123。

对于“abc1000def”,1000。

对于“555abc45”,555。

对于“abc”,将返回一个空字符串。

回答by Narendra

The code below is enough for "Check if a String contains numbers in Java"

下面的代码足以“检查字符串是否包含 Java 中的数字”

Pattern p = Pattern.compile("([0-9])");
Matcher m = p.matcher("Here is ur string");

if(m.find()){
    System.out.println("Hello "+m.find());
}

回答by Mallikarjuna Sangisetty

s=s.replaceAll("[*a-zA-Z]", "")replaces all alphabets

s=s.replaceAll("[*a-zA-Z]", "")替换所有字母

s=s.replaceAll("[*0-9]", "")replaces all numerics

s=s.replaceAll("[*0-9]", "")替换所有数字

if you do above two replaces you will get all special charactered string

如果您执行以上两次替换,您将获得所有特殊字符的字符串

If you want to extract only integers from a String s=s.replaceAll("[^0-9]", "")

如果你只想从一个整数中提取整数 String s=s.replaceAll("[^0-9]", "")

If you want to extract only Alphabets from a String s=s.replaceAll("[^a-zA-Z]", "")

如果您只想从一个字母中提取字母 String s=s.replaceAll("[^a-zA-Z]", "")

Happy coding :)

快乐编码:)