Umair Ayub
Umair Ayub

Reputation: 21271

Extract all numbers from a string along with their signs - Python 2.7

How do I extract all numbers along with sign?

Strings can be like these -1+110, +20-123 and +23-432-543

I am using this simple regular expression

event_book_value = re.findall('\d+', event_book_value)

it returns the numbers but do not return along with signs.

Upvotes: 0

Views: 179

Answers (2)

ndnenkov
ndnenkov

Reputation: 36110

Add an optional sign in front of the number regex:

[+-]?\d+
  • [+-] - a character set that matches a single + or -
  • ? - makes the previous match one or zero times
  • \d+ - one or more digits

See it in action

Upvotes: 3

Tadhg McDonald-Jensen
Tadhg McDonald-Jensen

Reputation: 21453

something like this:

def signSplit(string):
    nums = []
    cur = ""
    signs = "+-"
    for c in string:
        if c in signs:
            if cur:#if there is a number (so not the very beginning) then add it to nums
                nums.append(cur)
            cur = c #start out with the cur storing the sign
        elif c.isdigit():
            cur+=c
        else:
            raise ValueError("unrecognised character: %r"%c)
    nums.append(cur)
    return nums


print(signSplit("+23-432-543"))

It may be too slow for your needs but it works in pure python so easy to make edits later.

Upvotes: 1

Related Questions