Python - 来自套接字数据的正则表达式通配符?

发布于 2024-09-16 22:07:15 字数 268 浏览 3 评论 0原文

我有一个关于 Python 中正则表达式的问题。这些表达式由从服务器读取的数据组成,通过套接字连接。我正在尝试在这些表达式中使用和读取通配符。示例:假设我运行一个聊天服务器。收到消息后,服务器会发送给所有客户端(JSmith 发送“大家好!”)。

我的问题是,如果有多个用户名(不仅仅是 JSmith),我怎样才能让客户端程序读取服务器发送的数据,而不是写“[用户名]发送“大家好!”,而是写“[ usernamehere]:大家好!”?

有没有办法将正则表达式通配符中的数据存储到变量中?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

素罗衫 2024-09-23 22:07:15

如果数据总是那么简单,则根本不需要使用正则表达式:

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

使用正则表达式(使用命名表达式):

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'))

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'))
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文