简体   繁体   English

正则表达式屏蔽 email 除了域之前的三个字符

[英]Regular expression to mask email except the three characters before the domain

I am trying to mask email address in the following different ways.我正在尝试通过以下不同方式屏蔽 email 地址。

  1. Mask all characters except first three and the ones follows the @ symbol.屏蔽除前三个字符之外的所有字符,那些字符跟在 @ 符号后面。 This expression works fine.这个表达式很好用。

    (?<=.{3}).(?=[^@]*?@) (?<=.{3}).(?=[^@]*?@)

    abcdefgh@gmail.com -> abc*****@gmail.com abcdefgh@gmail.com -> abc*****@gmail.com

  2. Mask all characters except last three before @ symbol.屏蔽除 @ 符号之前的最后三个字符之外的所有字符。

    Example: abcdefgh@gmail.com -> *****fgh@gmail.com示例:abcdefgh@gmail.com -> *****fgh@gmail.com

    I am not sure how to check for @ and do reverse match.我不确定如何检查 @ 并进行反向匹配。

Can someone throw pointers on this?有人可以对此提出指示吗?

Maybe you could do a positive lookahead:也许你可以做一个积极的前瞻:

.(?=.*...@)

See the online Demo查看在线演示

  • . - Any character other than newline. - 除换行符以外的任何字符。
  • (?=.*...@) - Positive lookahead for zero or more characters other than newline followed by three characters other than newline and @ . (?=.*...@) - 除换行符之外的零个或多个字符的正向前瞻,后跟除换行符和@之外的三个字符。

You could use a negated character class [^\s@] matching a non whitespace char except an @.您可以使用否定字符 class [^\s@]匹配除 @ 之外的非空白字符。 Then assert what is on the right is that negated character class 3 times followed by matching the @ sign.然后断言右边是否定字符 class 3 次,然后匹配 @ 符号。

In the replacement use *在更换使用*

[^\s@](?=[^@\s]*[^@\s]{3}@)
  • [^\s@] Negated character class, match a non whitespace char except @ [^\s@]否定字符 class,匹配除@之外的非空白字符
  • (?= Positive lookahead, assert what is on the right is (?=正向前瞻,断言右边是
    • [^@\s]* Match 0+ times a non whitespace char except @ [^@\s]*匹配 0+ 次除@以外的非空白字符
    • [^@\s]{3} Match 3 times a non whitespace char except @ [^@\s]{3}匹配 3 次非空白字符, @除外
    • @ Match the @ @匹配@
  • ) Close lookahead )关闭前瞻

Regex demo正则表达式演示


If there can be only a single @ in the email address, you could for example make use of a finite quantifier in the positive lookbehind:如果在 email 地址中只能有一个 @,您可以例如在正向后视中使用有限量词:

(?<=(?<!\S)[^\s@]{0,1000})[^\s@](?=[^@\s]*[^@\s]{3}@[^\s@]+\.[a-z]{2,}(?!\S))

Regex demo正则表达式演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM