Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

187
Views
Regex - Detect all *separated* usernames in a string

I am trying to detect all usernames following this form:

/@[a-zA-Z0-9_.-]{3,30}/

For example, in the following string

@eminem is singing with @rihanna

, the method must return

["@eminem", "@rihanna"]

I have tried the following:

function matchAllUsernames(str) {
  const pattern = /@[a-zA-Z0-9_.-]{3,30}/g;
  return [...str.matchAll(pattern)].flat();
}

const str = "@eminem is singing with @rihanna";

console.log(matchAllUsernames(str));

But... what if I try with this string?

@eminem@ndsoiosd is singing with @rihanna

In this case, the method must ignore @eminem and @ndsoiosd, because there is no sparation between them...

function matchAllUsernames(str) {
  const pattern = /@[a-zA-Z0-9_.-]{3,30}/g;
  return [...str.matchAll(pattern)].flat();
}

const str = "@eminem@ndodshuoc is singing with @rihanna";

console.log(matchAllUsernames(str));

How can I do that?

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

You can prepend an anchor for a non word boundary before the @ and assert a whitespace boundary to the right at the end of the pattern:

\B@[a-zA-Z0-9_.-]{3,30}(?!\S)

Regex demo

function matchAllUsernames(str) {
  const pattern = /\B@[a-zA-Z0-9_.-]{3,30}(?!\S)/g;
  return [...str.matchAll(pattern)].flat();
}

const str = "@eminem@ndodshuoc is singing with @rihanna";

console.log(matchAllUsernames(str));

To support also the characters . and - not being allowed before the next @ sign:

(?<!\S)@[a-zA-Z0-9_.-]{3,30}(?!\S)

Regex demo

about 4 years ago · Juan Pablo Isaza Report

0

You can match consecutive mentions and discard those matches and only extract mentions from other contexts:

function matchAllUsernames(str) {
  const pattern = /(?:@[\w.-]{3,30}){2,}|(@[\w.-]{3,30})/g;
  return Array.from(str.matchAll(pattern), x=>x[1]).filter(Boolean);
}

const str = "@sia@ndodshuoc and @eminem are singing with @rihanna";
console.log(matchAllUsernames(str));

Note that [A-Za-z0-9_] is equal to \w.

The (?:@[\w.-]{3,30}){2,}|(@[\w.-]{3,30}) regex matches two or more sequences of 3 to 30 word, . or - chars, or captures into Group 1 a sequence of 3 to 30 word, . or - chars (in another context).

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!