VOOZH about

URL: https://www.geeksforgeeks.org/dsa/extract-all-integers-from-a-given-string/

⇱ Extract all integers from a given String - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Extract all integers from a given String

Last Updated : 24 May, 2026

Given a string s consisting of lowercase letters, uppercase letters, digits, and special characters, extract all the integers present in the string and return them in the order they appear.

If no integers are present in the string, return an empty array.

Example:

Input: s = "1: Geeks for geeks, 2: geeksfor geeks, 3: forGeeksgeeks 56"
Output: [1, 2, 3, 56]
Explanation: 1, 2, 3, 56 are the integers present in s.

Input: s = "geeksforgeeks"
Output: []
Explanation: No integers present in the string.

Using String Traversal – O(n) Time and O(n) Space

The idea is to traverse the string character by character and collect consecutive digit characters to form integers. A temporary string is used to store digits while traversing. Whenever a non-digit character is encountered, the collected number is stored in the answer vector and the temporary string is cleared. After the traversal ends, any remaining number is also added to the result.

  • Traverse all characters of the string
  • If the current character is a digit, append it to the temporary string
  • If the temporary string is not empty, store it in the answer vector
  • After traversal, store any remaining number
  • Return the vector containing all extracted integers

Output
500 100 

[Regex Approach] Using Regular Expressions – O(n) Time and O(n) Space

The idea is to use regular expressions to directly find all continuous sequences of digits present in the string. The regex pattern \\d+ matches one or more consecutive digit characters.

  • Create a regex pattern: \\d+ → matches continuous digits
  • Use regex_search() to find integers in the string
  • Store every matched number in the result vector
  • Continue searching in the remaining suffix of the string
  • Return all extracted integers

Output
 500 100 
Comment
Article Tags:
Article Tags: