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

Viewed 109

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)
5 Answers

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.)

The following pattern will only match non negative numbers:

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

pattern.findall(text)

OUTPUT

['125', '8969', '4788', '158', '599']

Your pattern ^[+]?\d+ is anchored at the start of the string, and will give only that match at the beginning.

Another option is to assert a whitspace boundary to the left, and match the optional + followed by 1 or more digits.

(?<!\S)\+?\d+\b
  • (?<!\S) Assert a whitespace boundary to the left
  • \+? Match an optional +
  • \d+\b Match 1 or more digits followed by a word bounadry

Regex demo

Use , to sperate the numbers in the string.

Related