简体   繁体   中英

Python regular expression dot character

I have solved this problem via Wiktor Stribiżew's suggestion.

Edited: I only need to extract the first element of the list at a time, because I need to do other operations on that number. I use a loop in my code just for testing.

I want to split an arithmetic expression into a list of numbers.

For example: 1+0.2-(3^4)*5 -> ['1', '0.2', '3', '4', '5']

I use the re library in python, but the expression is split with a dot character '.' although I do not include '.' in the delmiters.

Namely, when input is 1+0.2, the output will be ['1', '0', '2'], which should be ['1', '0.2']

The code is below:

#!/bin/python
import re

delims = re.compile(r"[+-/*///^)]")

while True:
    string = input()
    res = list()
    i = 0
    while i < len(string):
        if string[i] >= '0' and string[i] <= '9':
            num_str = delims.split(string[i:], 1)[0]
            res.append(num_str)
            i += len(num_str) - 1
        i += 1
    print(res)

I really appreciate any opinion to this question!

Use the following approach with re.findall function:

num_str = '1+0.2-(3^4)*5'
numbers = re.findall(r'\d(?=[^.]|$)|\d+\.\d+', num_str)

print(numbers)

The output:

['1', '0.2', '3', '4', '5']

If you only want to extract only positive integers, try the following. Ive assumed that were spaces between the simbols and numbers:

[int(s) for s in str.split() if s.isdigit()]

This is better than the regex example for three reasons: You don't need another module, It's more readable because you don't need to parse the regex mini-language and It is faster.

The reason your approach is not working is that you create a character range with +-/ which contains the dot. I also think you are overcomplicating things.

import re
str = '1+0.2-(3^4)*5'
res = re.split(r'[-+()/*^]+', str)
print(res)

will output ['1', '0.2', '3', '4', '5']

Please note that this approach won't handle negative numbers correctly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM