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

180
Views
Regex - negative lookahead & respond based on match length

I read a bit in this article, but I am not sure why I am failing:

Output.replaceAll("(?<=\s)(?!<).*(?=@)", "xxxx")

As an example, this will be the sample text:

To: <username@gmail.com>
I sent an e-mail to username@gmail.com yesterday

Here, what I want to achieve is replace username in username@gmail.com to "xxxx".

I already have a regex for replacing username in <username@gmail.com>, which works like a charm:

Output.replaceAll("(?<=<).*(?=@)", "xxxx")

Any idea what I am doing wrong?

By the way, I am replacing with hardcoded "xxxx" because I do not understand how to replace with certain amounts of "x" based on the length of the matched result. For example, "username" is 8 characters, so I want to replace it with "x" 8 times ("xxxxxxxx"). Any idea what I should be looking at to learn that? I googled a few times but never found any articles, so I guess I just do not know the right terminology.

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

0

Note that \G is not supported by Javascript.

You can match 1+ chars other than not allowed characters and then match the @ and then in the replacement repeat the x char and subtract 1 from the length.

[^\s@<>]+@

See a regex demo.

    const regex = /[^\s@<>]+@/g;
    const str = `To: <@gmail.com>
I sent an e-mail to a@gmail.com yesterday

To: <aa@gmail.com>
I sent an e-mail to aaa@gmail.com yesterday`;
    console.log(str.replace(regex, m => `${'x'.repeat(m.length - 1)}@`));

about 4 years ago · Juan Pablo Isaza Report

0

You can replace .* in your regex with [^\s]+.

As for replacing with xxx, replaceAll function can accept a function as a replacer:

console.log(
    "I sent an e-mail to username@gmail.com yesterday".replaceAll(
    /(?<=\s)(?!<)[^\s]+(?=@)/g, 
    (...match) => {
        let username = match[0]
        let replacer = ""
        for (let i = 0; i < username.length; i++){
            replacer += "x"
        }
        return replacer
    })
)

You can read about it here

about 4 years ago · Juan Pablo Isaza Report

0

You can match any non space character followed by any combination of non-space characters and the @ symbol.

[^\s<](?=\S*@)

Check the demo here.

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!