Extract Numbers from String

  • Share this:

Code introduction


Extracts all numbers from the input string and returns them as a list of integers.


Technology Stack : Regular expressions (re), string methods (findall), list comprehension

Code Type : Function

Code Difficulty : Intermediate


                
                    
import math
import os
import random
import re
import sys
import time

def extract_numbers_from_string(input_string):
    """
    从字符串中提取所有数字。
    """
    # 使用正则表达式匹配所有数字
    numbers = re.findall(r'\d+', input_string)
    # 将匹配到的数字字符串转换为整数
    numbers = [int(num) for num in numbers]
    return numbers