Home > database >  Regex - negative lookahead & respond based on match length
Regex - negative lookahead & respond based on match length

Time:06-07

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: <[email protected]>
I sent an e-mail to [email protected] yesterday

Here, what I want to achieve is replace username in [email protected] to "xxxx".

I already have a regex for replacing username in <[email protected]>, 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.

CodePudding user response:

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 [email protected] 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

CodePudding user response:

You can either match:

  • the first character, followed by not space-like characters and a @ symbol
  • any character after your last character match \G\w

Here's the regex:

\w(?=[^\s] @)|(?!^)\G\w

Check the demo here.

  • Related