ono
ono

Reputation: 3102

Regex for ignoring first and last character

Trying to obfuscate an email to this format:

a***@******m

Meaning I need a regex to match everything except first and last character, as well as @. I can use [^@] for everything but how do I ignore the last and first characters in a String? Anchors seem like the way to go but what is the exact syntax?

Upvotes: 2

Views: 10132

Answers (3)

The fourth bird
The fourth bird

Reputation: 163342

There is no language tagged, but if you are using a programming language and you want to make sure that there is an @ sign in the email address and that the first and last character are shown, you might use capturing groups and use replace on the groups that you want to show with an *:

^(\S)([^@\n]*)(@)([^@\n]*)(\S)$
  • ^ Start of string
  • (\S) Capture group 1, match a non whitespace char
  • ([^@\s]*) Capture group 2, match 0+ times not an @ or a whitespace char
  • (@) Capture group 3, Match @
  • ([^@\s]*) Capture group 4, match 0+ times not an @ or a whitespace char
  • (\S) Capture group 5, match a non whitespace char
  • $ End of string

Regex demo

For example using javascript

let pattern = /^(\S)([^@\s]*)(@)([^@\s]*)(\S)$/;
[
  "[email protected]",
  "te st@te st.com",
  "test@[email protected]",
  "te@nl",
  "t@t",
  "test@",
  "@tes",
  "test"
].forEach(str => {
  let replaced = str.replace(pattern, function(_, g1, g2, g3, g4, g5) {
    return g1 + g2.replace(/./g, "*") + g3 + g4.replace(/./g, "*") + g5;
  });
  console.log(replaced);
});

Upvotes: 0

blhsing
blhsing

Reputation: 106553

If the tool or language you use supports lookarounds, you can use:

(?<!^)[^@](?!$)

Demo: https://regex101.com/r/5Tbaq7/1

Upvotes: 3

bobble bubble
bobble bubble

Reputation: 18490

How about using a lookahead:

(?!^|.$)[^@\s]

See this demo at regex101

I also added white space to the characters that won't be replaced.

Upvotes: 7

Related Questions