Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

428
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda