Reputation: 21271
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
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 digitsUpvotes: 3
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