const regex = /^[^\S\n]*(\w+(?: +\w+)*?)(?=:| joined the lobby$)/gm;
// Alternative syntax using RegExp constructor
// const regex = new RegExp('^[^\\S\\n]*(\\w+(?: +\\w+)*?)(?=:| joined the lobby$)', 'gm')
const str = `Hey Guys,
I want to filter the usernames out of the following string from a game lobby:
Username123 joined the lobby
User name 123 joined the lobby
Otheruser 12 joined the lobby
Username123: Hello Guys!
o t h e ruser23 joined the lobby
Player1 3 joined the lobby
As you can see, the username can consist of characters, numbers and spaces. Before every Username a new line starts and the "joined the lobby" part is fixed. However between 2 users joining an already joined user can write a textmessage to the whole lobby.
How can I extract the 5 unique usernames?
I joined the lobby
`;
// Reset `lastIndex` if this regex is defined globally
// regex.lastIndex = 0;
let m;
while ((m = regex.exec(str)) !== null) {
// This is necessary to avoid infinite loops with zero-width matches
if (m.index === regex.lastIndex) {
regex.lastIndex++;
}
// The result can be accessed through the `m`-variable.
m.forEach((match, groupIndex) => {
console.log(`Found match, group ${groupIndex}: ${match}`);
});
}
Please keep in mind that these code samples are automatically generated and are not guaranteed to work. If you find any syntax errors, feel free to submit a bug report. For a full regex reference for JavaScript, please visit: https://developer.mozilla.org/en/docs/Web/JavaScript/Guide/Regular_Expressions