/PM 用于在聊天室发送消息的正则表达式语法
我正在开发一个 AJAX/PHP 聊天室,目前一直在使用正则表达式来检测用户是否发送了 PM & 消息。然后弄清楚它是谁以及消息是什么。
如果用户输入类似的内容
/pm PezCuckow 嗨,你太棒了!
我想首先测试我的字符串是否与该模式匹配,然后获取“PezCuckow”和“嗨,你太棒了!”作为要发布到 PHP 的字符串。
我对正则表达式做了一些研究,但真的不知道从哪里开始! 你能帮忙吗?
==感谢大家的帮助,现在已经解决了!==
var reg = /^\/pm\s+(\w+)\s+(.*)$/i;
var to = "";
if(message.match(reg)) {
m = message.match(reg);
to = m[1];
message = m[2];
}
I am working on a AJAX/PHP chatroom and am currently stuck on the regex to detect if a user has send a PM & then work out who it is too and what the message is.
If the user types something like
/pm PezCuckow Hi There you so awesome!
I would like to first test if my string matched that pattern then get 'PezCuckow' and 'Hi There you so awesome!' as strings to post to the PHP.
I have done some research on regex but really have no idea where to start with this one!
Can you help?
==Thanks to everyones help this is now solved!==
var reg = /^\/pm\s+(\w+)\s+(.*)$/i;
var to = "";
if(message.match(reg)) {
m = message.match(reg);
to = m[1];
message = m[2];
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
假设名称字段中只有单词字符(无空格等)有效,这将执行您想要的操作:
Assuming that only word characters (no spaces, etc) are valid in the name field, this'll do what you want:
此正则表达式解析消息:
说明:
在您的情况下 (
"/pm PezCuckow Hi There you so Awesome!"
):在更一般的情况下(
“嗨,你太棒了!”
)请注意,正斜杠需要在 JavaScript 正则表达式文字中转义:
但通常在正则表达式模式中不需要转义。
This regex parses a message:
Explanation:
In your case (
"/pm PezCuckow Hi There you so awesome!"
):in a more general case (
"Hi There you so awesome!"
)Note that the forward slash needs to be escaped in JavaScript regex literals:
but not in regex patterns in general.
怎么样:
匹配
"/pm"
后跟空格" "
(随意接受额外的空格),后跟用户名\w+
,接下来是空格" "
agin,最后是消息.*
(基本上是到行尾的所有内容)。Hows about this:
That matches
"/pm"
followed by whitespace" "
(liberally accepting extra spaces), followed by the username\w+
, followed by whitespace" "
agin, then finally the message.*
(which is basically everything to the end of the line).