So I've made a bot for Reddit that listens for a specific string that calls the bot into action. Well call that string, " !callme
". When you use this bot, you must provide a number after the call string, such as " !callme 1234
".
Currently, I have the bot set to remove " !callme
" and the spaces in the string, and if anything else exists after that, it posts a "failed" comment and tells the user to try again. What I want to do is have it remove literally everything from the comment EXCEPT the number string after the " !callme
" string. I need this because it uses the number in a mathematical operation, and if the final value isn't a digit, it fails and tells the user they did it wrong.
For example: " !callme 12345
" would work and post the correct comment, but " !callme helloworld
" would fail and post the comment telling them the correct format.
I want to skip that step and strip everything but the number string after the "!callme" string. Basically, if the user writes a sentence before calling the bot, it would fail. I want to change that.
The code I have now is below for the current working strip.
g = comment.body
pattern = re.compile(r'\s+')
g = re.sub(pattern, '', g)
g = g.replace('!callme', '')
if g.isdigit():
g = int(g)
else:
bad comment here
data_entry(com_id, com_auth, 1)
print("Bad comment found! Posting reply to comment " + comment.id + "!")
if isinstance(g, int):
cp = float(g / 100)
pa = float(cp / 10)
good comment here
There's some other try
statements with the comments, but that doesn't matter for this.
How could I go about doing this? Also if this code here is not optimal, feel free to correct me.
If i got your question correctly, would something like this fit?
g = "!callme XXX"
pat = re.compile(r'[0-9]+')
num = re.findall(pat, g) # num = []
g = "!callme 1234"
num = re.findall(pat, g) # num = '1234', now you could int(num)
or you can use a more precise regex such as
g = "!callme 1234"
pat = re.compile(r'(\!callme[ ]*)([0-9]+)')
m = re.search(pat, g)
# and go directly to group 2 which should be the num
print m.group(2) # this prints 1234, then int(m.group(2))
Here i define two groups, one for the callme part and the other for the numeric part
This should match the number you want.
pattern = re.compile(".*!callme +(\d+).*")
result = re.findall(pattern, g)
if result:
g = int(result[0])
Pattern explanation: .*!callme +(\\d+).*
.*
match anything before !callme
+
match at least one space after !callme
(\\d+)
match at least one digit
.*
match any chars after
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.