Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: How to use re by defining an exception?

Tags:

python

regex

This is a very newbie's question. I tried a lot on my own, but without success.

I want to use re to find numbers from a string, but with exception of the minus symbol:

>>> a1 = "25 mm"
>>> b1 = "-25 mm"
>>> c1 = "s-25"
>>> d1 = "s25-"

a = re.sub(r'\D', "", a1) gives "25", which is fine.

I would like to ask, how to use re for b1 and c1 to get "-25", and how to for d1 to get "25", because the minus symbol is behind the nummber.

Thanks for the help!

like image 669
Rt Rtt Avatar asked Jul 17 '26 17:07

Rt Rtt


1 Answers

here you can try this one :

import re
s = re.compile(r"[+-]?\d+(?:\.\d+)?")
a1 = "25 mm"
b1 = "-25 mm"
c1 = "s-25"
d1 = "s25-"
print(s.search(d1).group(0))
print(s.search(b1).group(0))
print(s.search(c1).group(0))
print(s.search(a1).group(0))

it gives the o/p like this :

25 #d1
-25 #b1
-25 #c1
25 #a1
like image 166
Vikas Periyadath Avatar answered Jul 19 '26 05:07

Vikas Periyadath



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!