Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

433
Vistas
Wny it does not give all positive numbers in the string? Regex in Python

I don't understand why it only gives 125, the first number only, why it does not give all positive numbers in that string? My goal is to extract all positive numbers.

import re

pattern = re.compile(r"^[+]?\d+")

text = "125 -898 8969 4788 -2 158 -947 599"

matches = pattern.finditer(text)

for match in matches:
    print(match)
over 4 years ago · Santiago Trujillo
3 Respuestas
Responde la pregunta

0

Try using the regular expression

-\d+|(\d+)

Disregard the matches. The strings representing non-negative integers are saved in capture group 1.

Demo

The idea is to match but not save to a capture group what you don't want (negative numbers), and both match and save to a capture group what you do want (non-negative numbers).

The regex attempts to match -\d+. If that succeeds the regex engine's internal string pointer is moved to just after the last digit matched. If -\d+ is not matched an attempt is made to match the second part of the alternation (following |). If \d+ is matched the match is saved to capture group 1.

Any plus signs in the string can be disregarded.

For a fuller description of this technique see The Greatest Regex Trick Ever. (Search for "Tarzan"|(Tarzan) to get to the punch line.)

over 4 years ago · Santiago Trujillo Denunciar

0

The following pattern will only match non negative numbers:

pattern = re.compile("(?:^|[^\-\d])(\d+)")

pattern.findall(text)

OUTPUT

['125', '8969', '4788', '158', '599']
over 4 years ago · Santiago Trujillo Denunciar

0

For the sake of completeness another idea by use of \b and a lookbehind.

\b(?<!-)\d+

See this demo at regex101

over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda