views:

53

answers:

1

Hello everyone. I have a question regarding regular expressions in Python. The expressions are composed of data that would be read from a server, connected via socket. I'm trying to use and read wildcards in these expressions. Example: Let's say I run a chat server. When a message is recieved, the server sends to all clients (JSmith sends "Hello everyone!").

My question is, if there are multiple usernames(not just JSmith), how can I have the client programs read the data sent by the server, and instead of writing "[username] sends "Hello everyone!", have it write "[usernamehere]: Hello everyone!"?

is there a way to store data from Regular expression wildcards into variables?

+1  A: 

If the data is always that simple, you do not need to use regular expresssions at all:

line = 'JSmith sends "Hello everyone!"'
user, data = line.split(' sends ', 1)
# remove the quotes
data = data[1:-1]
print "%s: %s" % (user, data)

With regular expressions (using named expressions):

import re
line = 'JSmith sends "Hello everyone!"'
chatre = re.compile('^(?P<user>\S+) sends "(?P<data>.*)"$')
m = chatre.match(line)
if m:
    print "%s: %s" % (m.group('user'), m.group('data'))
tonfa