Home > Net >  How to get number and calculating operator from string
How to get number and calculating operator from string

Time:06-07

I want to extract numer and calculator operator from string.

For example, I have a string like below:

1m-2m (2.2*3mm)

I want to get 1-2 (2.2*3) which will only contains number and -*/ and other operators.

Is there any way to achieve this?

I thought to achieve through regex. But, not sure the correct regex pattern.

CodePudding user response:

In the simple case you describe I suggest not to cope with regex patterns and process the text string character by character:

Let's use Python3 (as easy to read and understand programming language):

list_of_text_lines = [
    '1m-2m (2.2*3mm)'   , # test text 1
    '5z=25x-20y'        , # test text 2
    '11 != 12 ; 12 < 13', # test text 3   
]
for text_line in list_of_text_lines:
    s1 = ''.join( [ 
          char for char in text_line 
       if char in "0.123456789 -*/=()<>^!;" ] ) 
    print(s1)
# gives: 
"""
1-2 (2.2*3)
5=25-20
11!=12;12<13
"""

where you can intuitively and easy adapt the code to the details of what you need.

  • Related