Open In App

Extract all integers from the given String in Java

Last Updated : 21 Nov, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

In Java, we can extract integers from a given string using several approaches such as regular expressions, character iteration, or the split() method. In this article, we will learn how to extract all integers from the given String in Java.

Example:

We will use regular expressions to extract all integers from a given string. For this, we will use the Pattern and Matcher classes with the regex "\\d+".

Java
// Java program to extract integers from a string 
// using regex

import java.util.regex.*;
import java.util.*;

public class Extract {
  
    public static void main(String[] args) {
      
        String i = "Java 123 is a Programming 456 Language.";

        // Compile the regex to match integers
        Pattern pattern = Pattern.compile("\\d+");
        Matcher matcher = pattern.matcher(i);

        // Extract integers
        List<Integer> n = new ArrayList<>();
        while (matcher.find()) {
            n.add(Integer.parseInt(matcher.group()));
        }

        System.out.println("" + n);
    }
}

Output
[123, 456]

Other Ways to Extract Integers from a String

Apart from regular expressions, there are other effective methods to extract integers from a string. We will dicuss them below:

1. Using Character Iteration

This method iterates through each character in the string by identifying numeric characters, and building numbers step by step.

Example:

Java
// Java program to extract integers from a given string

public class Extract {

    public static void main(String[] args) {
      
        String s = "abc123def456ghi";
        StringBuilder r = new StringBuilder();

        boolean wasDigit = false; // Flag to track if the previous character was a digit

        // Iterate through each character in the string
        for (char c : s.toCharArray()) {

            if (Character.isDigit(c)) {
                r.append(c);  
                wasDigit = true; // Mark that we are in a digit sequence
            } else if (wasDigit) {
              
                // Append a space only after a sequence of digits ends
                r.append(" ");
                wasDigit = false; // Reset flag for non-digit characters
            }
        }

        // Convert StringBuilder to String and print
        String a = r.toString().trim();
        System.out.println(a.isEmpty() ? "-1" : a);
    }
}

Output
123 456


2. Using replace() and trim() to Extract Integers

This approach replaces non-digit characters with spaces by using replace() method, removes extra spaces, and trims the string to isolate integers from the input by using trim() method.

Example:

Java
// Java program to demonstrate extracting integers from a given string
public class GFG {

    // Function to return the modified string
    static String extractInt(String s) {
        
        // Replacing every non-digit character with a space (" ")
        s = s.replaceAll("[^\\d]", " ");

        // Remove extra spaces from the beginning and the end of the string
        s = s.trim();

        // Replace all consecutive white spaces with a single space
        s = s.replaceAll(" +", " ");

        // Return -1 if the string is empty
        if (s.equals("")) {
            return "-1";
        }

        return s;
    }

    public static void main(String[] args) {
        String s = "avbkjd123klj 456 af";
        System.out.print(extractInt(s)); 
    }
}

Output
123 456



Next Article
Practice Tags :

Similar Reads