Need help with my code (Regular Expression)

Hi there,

I am new to the world of python, sorry for my primitive question!

Here is my code

import re
import collections

txt = “MCV L +67 -34 83.0 - 101.0 fL something”
result = re.findall(r"[-|+]?([0-9]*.[0-9]+|[0-9]+)", txt)
word = re.findall(r"\s(mm|milj./µL|g/dL|%|fL|pg|/µL|something)", txt)

def get_number_of_elements(list):
count = 0
for element in list:
count += 1
return count

count = get_number_of_elements(result)

for i in range (0,count):
print (result[i])

print(“Value is”,result[0])
print (“Range is”, result[1] + " - " + result[2],word[0])

Here is my question →
I was hoping result will give me +67 and -34 but it gives me 67, 34.
Although I have added optional + or - to be recognized, it never takes that into account.
What am I missing ? Please help!
Thanks in advance

Cross-posted to Need help with my code (regular expression).

Among other things, your character class for the sign is outside the capturing parentheses, so when it matches it is not placed in the result.

thanks for response, upon little more research … figured this expression does the trick →
result = re.findall(r"[-+]?[0-9]*.?[0-9]+", txt)

The dot should also be escaped so it doesn’t match something other than a decimal point.

1 Like