Reputation: 454
I have the following regular expression pattern that can find all the players that a person has tagged in a message:
/(?<=.*)(?<=[@])([a-zA-Z0-9]){1,16}(?=[ ].*)(?=.{2,})/
@benjamin @tyler @joe @nic Hello!
And the following regular expression can select the entirety of the tagging text:
/([@]([a-zA-Z0-9]){1,16}[ ]){1,}/
@benjamin @tyler @joe @nic Hello! (includes space before "Hello!" and between tagged players)
However, I want a method to grab just the body of the message, such as:
@benjamin @tyler @joe @nic Hello!
What sort of pattern would I use to achieve this?
Upvotes: 3
Views: 281
Reputation: 3057
Perhaps:
(?:[@](?:[a-zA-Z0-9]){1,16}[ ]){1,}(.*)
If multiline is also included in the message:
(?:[@](?:[a-zA-Z0-9]){1,16}[ ]){1,}((?:.|\s)*)
Note: these won't pull out usernames from the middle of the body
If you want to pull out all referenced usernames:
/(?:(@\w{1,16})\b){1,}/g
Yours at current will just pull out the last one.
Edit
In fact, using the last regex there:
function getUsernamesAndBody(message) {
let regex = /(?:(@\w{1,16})\b){1,}/g,
info = {
body: message,
usernames: []
}
do {
match = regex.exec(message);
if (match) {
info.usernames.push(match[1])
}
} while (match);
info.usernames.forEach((username) => {
info.body = info.body.replace(username, "").trim();
});
return info
}
let fullMessage = `@benjamin @tyler @joe @nic Hello! Hi @john
Hi Guys`;
console.log(getUsernamesAndBody(fullMessage))
It will add multiple of the same username to the array, but you can add a check in there if you wanted to only capture a single mention. This also means that if a username is mentioned in the middle of the body, you have captured that and removed it from the body (if that is not needed, then some rework can be done)
Upvotes: 2
Reputation: 2591
I believe this works.
console.log(/([@]([a-zA-Z0-9]){1,16}[ ]){1,}((.|\s)*)/.exec("@benjamin @tyler @joe @nic Hello\nnewlines work too! oi*)&) hjoi[JPOIJ(N#* Any character works yay! Even the @ symbol!")[3]);
Upvotes: 1
Reputation: 8617
/([@]([a-zA-Z0-9]){1,16}[ ]){1,}(.+)/.exec(`@benjamin @tyler @joe @nic Hello!`)[matchingGroup]
where matching group in this case is 3, because it is your third set of parenthesis.
Upvotes: 1