Extract all integers from the given string in Java

Given a string str consisting of digits, alphabets and special characters. The task is to extract all the integers from the given string.

Examples:

Input: str = “geeksforgeeks A-118, Sector-136, Uttar Pradesh-201305”
Output: 118 136 201305



Input: str = ” 1abc35de 99fgh, dd11″
Output: 1 35 99 11

Approach:

  • Replace all the non-digit characters with spaces (” “).
  • Now replace every consecutive group of spaces with a single space.
  • Eliminate the leading and the trailing spaces (if any) and the final string will only contain the required integers.

Below is the implementation of the above approach:

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java implementation of the approach
public class GFG {
  
    // Function to return the modified string
    static String extractInt(String str)
    {
        // Replacing every non-digit number
        // with a space(" ")
        str = str.replaceAll("[^\\d]", " ");
  
        // Remove extra spaces from the beginning
        // and the ending of the string
        str = str.trim();
  
        // Replace all the consecutive white
        // spaces with a single space
        str = str.replaceAll(" +", " ");
  
        if (str.equals(""))
            return "-1";
  
        return str;
    }
  
    // Driver code
    public static void main(String[] args)
    {
        String str = "avbkjd1122klj4 543 af";
        System.out.print(extractInt(str));
    }
}

chevron_right


Output:

1122 4 543


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :
Practice Tags :


1


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.