2

I was wondering how to go about finding a string you don't know what is, in a string. I am writing an IRC bot and i need this function. I want to be able to write:

!greet Greg

and then my bot is supposed to say "Hi, Greg!". So what comes after greet is variable. And if i wrote !greet Matthew it would say "Hi, Matthew!". Is this possible?

Thanks a lot.

Andesay

Andesay
  • 229
  • 2
  • 4
  • 9

5 Answers5

3
if command.lower().startswith('!greet '):
    put('Hi, ' + command[7:].strip() + '!')

'!greet Greg' -> [ put()s 'Greg' ]
'!Greet  Fred ' -> [ put()s 'Fred' ]
'!hello John' -> [ nothing ]
dan_waterworth
  • 6,261
  • 1
  • 30
  • 41
3
import re
...
input = '!greet Greg'
m = re.match(r'!greet\s+(.*)', input)
if m:
    print 'Hi, %s!' % m.group(1)
Laurence Gonsalves
  • 137,896
  • 35
  • 246
  • 299
  • 3
    People who downvote and don't bother to leave a comment explaining what is wrong is frustrating. +1 though. – user225312 Dec 12 '10 at 17:51
  • I didn't downvote, but I imagine they did it because you used `re.match` and then an if construct when you could've used a more appropriate function from `re`. – Rafe Kettler Dec 12 '10 at 17:53
  • Or perhaps they felt that using regular expressions was overkill for this question, when dan_waterworth's solution works perfectly well. – Tyler Dec 12 '10 at 18:27
  • @Rafe and @MatrixFrog Based on the question I assumed the OP would eventually want to add other commands to their system -- ones where regular expressions would be useful and where the more general solution of using `match` would work but `sub` might not. – Laurence Gonsalves Dec 12 '10 at 18:37
3

If you plan on adding more complexity to your bot, i would suggest using regular expressions like this:

At first you define the functions your bot may need.

def greet_user(name):
    print 'Hello, %s' % name

Then you define the pattern and a dict of commands:

import re
pattern = re.compile(r'!(?P<command>\w+)\s*(?P<args>\w*)')
commands = {'greet': greet_user}

Now you just have to call pattern.match() with the user input and the appropriate function:

m = pattern.match(string)
commands.get(m.group('command'))(m.group('args'))

If a user enters an invalid command, a TypeError is thrown.

Now you can add any function just by editing the commands-dict.

Nedec
  • 836
  • 10
  • 15
1

It's simple:

>>> import re
>>> m = re.search(r"!greet (?P<name>.+)", "!greet Someone")
>>> m.group("name")
'Someone'
Menda
  • 1,783
  • 2
  • 14
  • 20
-1

if "Greg" in greet: doSomething("Hi Greg")

the key is that strings take the in operator

hunterp
  • 15,716
  • 18
  • 63
  • 115