Reputation: 14422
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];
}
Upvotes: 0
Views: 309
Reputation: 44642
Assuming that only word characters (no spaces, etc) are valid in the name field, this'll do what you want:
var re = /(\/\w+) (\w+) (.+)/;
Upvotes: 0
Reputation: 338308
This regex parses a message:
^(?:\s*/(\w+)\s*(\w*)\s*)?((?:.|[\r\n])*)$
Explanation:
^ # start-of-string
(?: # start of non-capturing group
\s*/ # a "/", preceding whitespace allowed
(\w+) # match group 1: any word character, at least once (e.g. option)
\s+ # delimiting white space
(\w*) # match group 2: any word character (e.g. target user)
\s+ # delimiting white space
)? # make the whole thing optional
( # match group 3:
(?: # start of non-capturing group, either
. # any character (does not include newlines)
| # or
[\r\n] # newline charaters
)* # repeat as often as possible
) # end match group 3
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:
/foo\/bar/
but not in regex patterns in general.
Upvotes: 2
Reputation: 24105
Hows about this:
var reg = /^\/pm\s+(\w+)\s+(.*)$/i,
m = '/pm PezCuckow Hi There you so awesome!'.match(reg);
m[0]; // "PezCuckow"
m[1]; // "Hi There you so awesome!"
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).
Upvotes: 1