Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

427
Views
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 answers
Answer question

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 Report

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!