Extract Numbers from String

Medium~15 min

Given a string, extract all integers (including negative) from it and return them as an array in the order they appear.

A negative number is defined as a '-' character immediately followed by one or more digits, where the '-' is either at the start of the string or preceded by a non-digit character.

For example:

  • "abc-3def45gh-6" returns [-3, 45, -6]
  • "no numbers here" returns []
  • "5-3" returns [5, -3] (the - is preceded by a digit 5, so 5 is one number and -3 is another)

Examples

Example 1
Input: s = "abc-3def45gh-6"
Output: [-3, 45, -6]
Explanation: Three numbers found: -3, 45, and -6.
Example 2
Input: s = "temperature is -20 degrees"
Output: [-20]
Explanation: One negative number found: -20.
Example 3
Input: s = "no numbers"
Output: []
Explanation: No digits in the string, so the result is an empty array.

Constraints

  • 0 <= s.length <= 10^4
  • s consists of printable ASCII characters.
  • All extracted numbers fit within 32-bit signed integer range.
Code
Ctrl+EnterRun|Ctrl+⇧+EnterSubmit
Output

Run your code to see results

Use Cmd+Enter to run