此正则表达式解析一条消息:
^(?:\s*/(\w+)\s*(\w*)\s*)?((?:.|[\r\n])*)$
解释:
^ # 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
在您的情况下("/pm PezCuckow Hi There you so awesome!"
):
- 第一组:“下午”
- 第 2 组:“PezCuckow”
- 第 3 组:“嗨,你真棒!”
在更一般的情况下 ( "Hi There you so awesome!"
)
- 第一组:“”
- 第 2 组:“”
- 第 3 组:“嗨,你真棒!”
请注意,正斜杠需要在 JavaScript 正则表达式文字中进行转义:
/foo\/bar/
但通常不是正则表达式模式。