Home > Software design >  Regex for detecting tagged @users
Regex for detecting tagged @users

Time:10-31

I am making an app where if a user has "@username" in a text, it tags them and sends notification. I tried to doing this by using this regex /\B(\@[a-zA-Z] \b)(?!;)/ this works but I dont want it to consider it valid when there is more than one "@". For example:

@username - valid

@@username - invalid

hey @username - valid

@usern@name - invalid

hey@username - invalid

CodePudding user response:

You can use regex ^@[a-z] $

enter image description here

function isValid(str) {
  const regex = /^@[a-z] $/;
  return str.split(" ").some((s) => regex.test(s));
}

console.log(isValid("@username"))
console.log(isValid("hey @username"))
console.log(isValid("@@username"))
console.log(isValid("@usern@name"))
console.log(isValid("hey@username"))
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

(?<=\s|^\s?)@[a-zA-Z] (?=\s|\s?$) might work.

const testcase = ['@username', '@@username', 'hey @username', '@usern@name', 'hey@username', 'hey @username hey', '@username hey'];

testcase.forEach(text => {
    console.log(text   ' => '   
        /(?<=\s|^\s?)@[a-zA-Z] (?=\s|\s?$)/.test(text)
    );
});
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

Regex that will help you acheive the task you want -

^@[A-z0-9_-.] $

Assuming that you will also encounter usernames such as -

@user.name

@user-name

@user_name

@user.name.

@User_name

  • Related