Denomi
Denomi

Reputation: 23

Discord.py extracting integers and floats within message content

I am currently working on a bot within Discord and in one of the functions I require it to be able to extract integers and floats from message content while ignoring anything else. I am wondering what would be the best way to do this while still keeping in mind mathematical operations (e.g if a message said "27+3 whats good dude" I would expect the variable to return "30"). Currently I am just extracting the whole message content and using that for my input however say someone were to put any text after they put the numbers (e.g "594 what's up man") it throws off the rest of the function as it requires a stripped integer or float value.

Here is the sample of the code that is currently being thrown off whenever a non-integer input is entered

Code Sample

and here are both examples of what I want the bot to require as correct inputs

Expecting 373:

First Error

Expecting 613:

Second Error

Upvotes: 0

Views: 201

Answers (1)

Pedro Caribé
Pedro Caribé

Reputation: 270

I think that the easiest way you'll achieve extracting numbers from the string is by using regex.

You can use Pythex to formulate your regex formula, but I believe the one that best suits your request would be this:

import re
string = "602,11 Are the numbers I would like to extract"

a = [int(i) for i in re.findall(r'\d+', string)]
a = [602, 11]

Now, Regular expressions (regex) can only be used to recognize regular languages. The language of mathematical expressions is not regular; So, for you to extract and parse a math expression from a string you'll need to implement an actual parser in order to do this.

Upvotes: 2

Related Questions