Java как найти все числа в строке

For example, I have input String: “qwerty1qwerty2“;

As Output I would like have [1,2].

My current implementation below:

import java.util.ArrayList;
import java.util.List;

public class Test1 {

    public static void main(String[] args) {
        String inputString = args[0];
        String digitStr = "";
        List<Integer> digits = new ArrayList<Integer>();

        for (int i = 0; i < inputString.length(); i++) {
            if (Character.isDigit(inputString.charAt(i))) {
                digitStr += inputString.charAt(i);
            } else {
                if (!digitStr.isEmpty()) {
                    digits.add(Integer.parseInt(digitStr));
                    digitStr = "";
                }
            }
        }
        if (!digitStr.isEmpty()) {
            digits.add(Integer.parseInt(digitStr));
            digitStr = "";
        }

        for (Integer i : digits) {
            System.out.println(i);
        }
    }
}

But after double check I dislake couple points:

  1. Some lines of code repeat twice.

  2. I use List. I think it is not very good idea, better using array.

So, What do you think?

Could you please provide any advice?

  1. Check if String Contains Numbers in Java
  2. Use the matches() Method to Check if String Contains Numbers in Java
  3. Use the replaceAll() Method to Check if String Contains Numbers in Java
  4. Use the isDigit() Method to Check if String Contains Numbers in Java
  5. Conclusion

Check if String Contains Numbers in Java

This article discusses the various ways to find a number from a string in Java.

Check if String Contains Numbers in Java

In Java, a string is simply a sequence of characters or an array of characters. However, it can contain numeric values too. A string looks like this.

String a = "Hello World!";

If we put in some numeric values, the string will look like this.

String a = "This is 123";

Note that putting numeric values in a string is not illegal. Look at the below program, for example.

import java.util.*;
public class Demo{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);

//Asking for a string input
System.out.println("How may we help you?");
String a = sc.nextLine();

System.out.println("Okay, thank you!");
}
}

Output:

How may we help you?
Find the cube of 10
Okay, thank you!

Note that the program runs fine even though the user had input a numeric value inside the string. But this leads to situations where we might need to find out if a number is present in a string or not.

This article will look at a few ways to do that.

Java has a class, the Java String class, which has a lot of methods to manipulate Java strings in different ways. To find out the presence of a number in a string, we can use some of the built-in methods provided by the Java library.

But before we start, as a prerequisite, we must also know about regex or regular expressions. Regex or Regular expressions is an API that helps edit, change, or manipulate strings in Java. It works based on string patterns.

Regex is mainly used to validate email addresses and check if a password meets the basic constraints. The java.util.regex package helps with regular expressions.

This package has three main classes for different purposes.

  • util.regex.Pattern: This is used for defining string patterns
  • util.regex.Matcher: This uses patterns to perform matching operations
  • PatternSyntaxException: This indicates any syntax error present in a regular expression

To know more about regex and patterns in Java, refer to this documentation.

Use the matches() Method to Check if String Contains Numbers in Java

The java string matches() method checks if a string matches the given regular expression. We can use it in two different ways.

Or

Pattern.matches(regex, string)

We get the same result by using either of the above ways. Let us look at an example.

import java.io.*;
public class Demo {

public static void main(String args[]) {
String Str = new String("We will learn about regular expressions");

System.out.println(Str.matches("(.*)regular(.*)"));

System.out.println(Str.matches("expressions"));

System.out.println(Str.matches("We(.*)"));
}
}

Output:

You must wonder that although the word expressions is present in the string, the output we get is false. We use a period and an asterisk in the other two patterns.

The use of a period . will match any character but not a newline character. For example, .article match particle but not article.

The asterisk *, on the other hand, is used to repeat expressions. To match a series of zero or more characters, we use the .* symbol.

Let us see how we can find if a string has a number.

import java.io.*;
public class Demo {

public static void main(String args[]) {
String Str = new String("The string has the number 10.");

//Using regular expressions
System.out.println(Str.matches("(.*)10(.*)"));

}
}

Output:

Note that we changed the last line and still get the same output. Here, the .* finds the occurrence of a character from 0 to infinite.

Then the double backslash escapes the second backslash to find a digit from 1 to infinite times.

We can also replace the \d with [0-9]. Look at the code for demonstration.

import java.io.*;
public class Demo {

public static void main(String args[]) {
String Str = new String("The string has the number 10.");

System.out.println(Str.matches(".*[0-9].*"));
}
}

Output:

All these methods return the result only in Boolean values. Other ways can give the number as output.

To learn more about the matcher class in Java, refer to this documentation.

Use the replaceAll() Method to Check if String Contains Numbers in Java

This method gives not just one but all the numbers present in a string. Here, we follow a three-step approach.

First, we replace the non-numeric characters with a space. Next, we merge consecutive spaces to one space, and lastly, we discard the trailing spaces such that the remaining string contains only numbers.

public class Demo{
static String FindInt(String str)
{
//First we replace all the non-numeric characters with space
str = str.replaceAll("[^\d]", " ");

//Remove all the trailing spaces
str = str.trim();

//Replace consecutive white spaces with one white space
str = str.replaceAll(" +", " ");

if (str.equals(""))
return "-1";

return str;
}
public static void main(String[] args)
{
String str = "gibberish123gibberish 456";
System.out.print(FindInt(str));
}
}

Output:

We use the replaceAll() method, which takes the regex string and the replacement string. It returns a string replacing the characters that match the regex and replacement string.

Syntax:

string.replaceAll(String regex, String replacement)

Then we use the trim() method to discard the leading and trailing spaces. Java does that with the help of the Unicode value of space u0020.

Note that the trim() method does not remove the spaces between the string. It only checks for the spaces at the string’s ending and starting.

Syntax:

Use the isDigit() Method to Check if String Contains Numbers in Java

To find an integer from a string, we can use this in-built function called isDigit(). But before this, we have to convert the string to a character array. Look at the example.

public class Demo {
public static void main(String args[]){
String example = "Find the square of 10";
char[] ch = example.toCharArray();
StringBuilder strbuild = new StringBuilder();
for(char c : ch){
if(Character.isDigit(c)){
strbuild.append(c);
}
}
System.out.println(strbuild);
}
}

Output:

We first use the toCharArray() method to convert the string to an array of characters. The length of the newly allocated array and the previous string is the same.

Syntax:

Then, we can use the isDigit() method on each element in the array to find if the string has any numbers.

Conclusion

In this article, we saw how to find a number from a string in Java. To do this, we can use regex in many ways. But regex gives the output as a Boolean value.

To get the output as a number, we can use the replaceAll() method with the trim() method. We can also use the Java isDigit() method to find numbers from a string.

Для извлечения чисел из строки в Java можно использовать регулярные выражения. Для этого можно воспользоваться классом Pattern и Matcher:

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Main {
    public static void main(String[] args) {
        String str = "abc123def456ghi789";
        Pattern pattern = Pattern.compile("\d+");
        Matcher matcher = pattern.matcher(str);

        while (matcher.find()) {
            System.out.println(matcher.group());
        }
    }
}

В данном примере мы

  • создаем объект Pattern, используя регулярное выражение d+, которое означает “один или более цифр”
  • создаем объект Matcher, который будет использоваться для поиска соответствий в строке str
  • используем метод find() для поиска следующего соответствия, и метод group() для получения найденного числа.
    Метод find() будет продолжать искать числа, пока они есть в строке.

В результате выполнения кода будут выведены следующие числа:

123
456
789

The following are examples which show how to extract numbers from a string using regular expressions in Java.

Being able to parse strings and extract information from it is a key skill that every tester should have. This is particularly useful when testing APIs and you need to parse a JSON or XML response.

The following Java Regular Expression examples focus on extracting numbers or digits from a String.

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class RegexExamples {
    public static void main(String[]args) {
        Pattern p = Pattern.compile("\d+");
        Matcher m = p.matcher("string1234more567string890");
        while(m.find()) {
            System.out.println(m.group());
        }
    }
}

Output:

1234
567
890
  • How to convert String to Int in Java
  • How to reverse Strings in Java
  • How to compare Strings in Java

If you want to extract only certain numbers from a string you can provide an index to the group() function.

For example, if we wanted to only extract the second set of digits from the string string1234more567string890, i.e. 567 then we can use:

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class RegexExamples {
    private static final Pattern p = Pattern.compile("[^\d]*[\d]+[^\d]+([\d]+)");
    public static void main(String[] args) {
        // create matcher for pattern p and given string
        Matcher m = p.matcher("string1234more567string890");

        // if an occurrence if a pattern was found in a given string...
        if (m.find()) {
            System.out.println(m.group(1)); // second matched digits
        }
    }
}

Output:

567

Explanation of the Pattern [^d]*[d]+[^d]+([d]+)

  • ignore any non-digit
  • ignore any digit (first number)
  • again ignore any non-digit
  • capture the second number

When dealing with XML or HTML tags, sometimes there is a need to extract a value from an attribute. For example, consider the following tag

<result name="response" numFound="9999" start="0">

To extract number 9999 we can use the following code:

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class RegexExamples {
    public static void main(String[]args) {
        Pattern pattern = Pattern.compile("numFound="([0-9]+)"");
        Matcher matcher = pattern.matcher("");

        if (matcher.find()) {
            System.out.println(matcher.group(1));
        }
    }
}

Output:

9999

Extract a String Containing digits and Characters

You can use Java regular expressions to extract a part of a String which contains digits and characters. Suppose we have this string Sample_data = YOUR SET ADDRESS IS 6B1BC0 TEXT and we want to extract 6B1BC0 which is 6 characters long, we can use:

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class RegexExamples {
    public static void main (String[] args) {
        Pattern p = Pattern.compile("YOUR SET ADDRESS IS\s+([A-Z0-9]{6})");
        Matcher n = p.matcher("YOUR SET ADDRESS IS 6B1BC0 TEXT");
        if (n.find()) {
            System.out.println(n.group(1)); // Prints 123456
        }
    }
}

Output:

6B1BC0

Let’s suppose we have a string of this format bookname=testing&bookid=123456&bookprice=123.45 and we want to extract the key-value pair bookid=123456 we would use:

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class RegexExamples {
    public static void main(String[] args) {
        String s = "bookname=cooking&bookid=123456&bookprice=123.45";
        Pattern p = Pattern.compile("(?<=bookid=)\d+");
        Matcher m = p.matcher(s);
        if (m.find()) {
            System.out.println(m.group());
        }
    }
}

Output:

123456

0 / 0 / 1

Регистрация: 24.01.2014

Сообщений: 51

1

Как в строке найти целые числа

04.04.2014, 20:51. Показов 16012. Ответов 5


Студворк — интернет-сервис помощи студентам

Здраствуйте . В java новичок, поэтому есть вопрос.Скажите как из строки найти целые числа.И записать их в массив int a [].(если не затруднит поставьте коментарии)



0



Programming

Эксперт

94731 / 64177 / 26122

Регистрация: 12.04.2006

Сообщений: 116,782

04.04.2014, 20:51

5

Freedomen

61 / 61 / 19

Регистрация: 06.09.2013

Сообщений: 236

Записей в блоге: 1

04.04.2014, 23:38

2

Лучший ответ Сообщение было отмечено viifelso как решение

Решение

Java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
public int[] getIntNums(String str) {
        int[] result = new int[lengthOfIntNums(str)];
        
        if(result.length == str.length()) {
            for(int i = 0; i < str.length(); i++) {
                result[i] = str.charAt(i) - '0';
            }
        } else {
            System.out.println("Какой-то элемент - не целое число.");
        }
        
        return result;
    }
    
    public int lengthOfIntNums(String str) {
        char[] nums = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };
        int length = 0;
        
        for(char elem : nums) {
            for(int i = 0; i < str.length(); i++) {
                if(elem == str.charAt(i)) {
                    length++;
                }
            }
        }
        
        return length;
    }



1



some_name

Вежливость-главное оружие

233 / 234 / 86

Регистрация: 19.02.2013

Сообщений: 1,446

05.04.2014, 00:30

3

Лучший ответ Сообщение было отмечено viifelso как решение

Решение

Лови!

Java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
import java.util.Arrays;
 
public class Main {
 
    public static void main(String[] args) {
 
    String data = "Hello! My age 100. Current time = 23:00";
    int[] digits = findDigits(data);
    int length = digits.length;
    for (int i = 0; i < length; ++i) {
        System.out.print(digits[i] + "  ");
    }
    }
 
    private static int[] findDigits(String str) {
    int length = str.length(), count = 0;
    char[] data = str.toCharArray();
    int[] result = new int[length];
    for (int i = 0; i < data.length; ++i) {
        if (Character.isDigit(data[i])) {
        result[count++] = Integer.parseInt(Character.toString(data[i]));
        }
    }
 
    return Arrays.copyOfRange(result, 0, count);
    }
}

//Out
1 0 0 2 3 0 0



2



0 / 0 / 1

Регистрация: 24.01.2014

Сообщений: 51

05.04.2014, 01:06

 [ТС]

4

Спасибо вам ребят.



0



tankomaz

ɐwʎ ɔ vǝmоɔ dиw ɐʚонɔ

443 / 442 / 100

Регистрация: 14.10.2012

Сообщений: 1,146

Записей в блоге: 9

05.04.2014, 01:22

5

Java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
    public static void main(String[] args) {
        List<Integer> integers = new ArrayList<>();
 
        String str = "123 sd sd 152 45 dfsvcx 949 34 3 jdfdgh 12,18 12,65 1,1";
 
        Pattern pattern = Pattern.compile("\d+\S?\d*");
        Matcher matcher = pattern.matcher(str);
        while(matcher.find()) {
            String s = matcher.group(0);
            if (s.replaceAll("\D", "").length() == s.length()) {
                integers.add(Integer.parseInt(s));
            }
        }
 
        System.out.println(integers);
    }

[123, 152, 45, 949, 34, 3]



1



0 / 0 / 1

Регистрация: 24.01.2014

Сообщений: 51

05.04.2014, 02:01

 [ТС]

6

Извиняюсь , но если не правильно понял код , в в обоих случаях массивы из строк сравниваются посимвольно. Т . e. строка “12kjj34jnjb565bj4bjbbj” получиться массивом 1234565 . А этого не должно быть!
она должна записана в массиве как 12 34 565

Добавлено через 58 секунд
tankomaz, спасибо



0



IT_Exp

Эксперт

87844 / 49110 / 22898

Регистрация: 17.06.2006

Сообщений: 92,604

05.04.2014, 02:01

Помогаю со студенческими работами здесь

Дан текстовый файл, содержащий целые числа. Найти максимальный элемент в каждой строке.
9.3. Дан текстовый файл, содержащий целые числа. Найти максимальный элемент в каждой строке.

Дан текстовый файл, содержащий целые числа. Найти максимальный элемент в каждой строке
Помогите ребята решить задачу!!! Дан текстовый файл, содержащий целые числа. Найти максимальный…

В исходной строке, содержащей перечисленные через пробел слова, найти целые положительные числа и составить из них новую строку
Задание:
В исходной строке, содержащей перечисленные через
пробел слова, найти целые…

Дан текстовый файл, содержащий целые числа. В каждой строке этого файла найти сумму наибольшего и наименьшего элементов и записать их в другой
Дан текстовый файл, содержащий целые числа. В каждой строке этого файла найти сумму наибольшего и…

Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:

6

Добавить комментарий