电子邮件屏蔽的正则表达式
Regular expression for email masking
我正在尝试编写一个正则表达式来屏蔽电子邮件地址。示例如下。
input: john.doe@example.en.com
output: j*******@e*********.com
我尝试了以下方法,但似乎无法正常工作。
regex:(?<=.).(?=[^@]\*?@)
output:j*******@example.en.com
regex:(?<=.).(?=[^@]\*?)(?=[^\.]\*?\.)
output:j******************.com
如有任何帮助,我们将不胜感激。
demo
如果您不需要具有与原始字符串(更匿名)相同字符数的掩码,这个怎么样:
(?<=^.)[^@]*|(?<=@.).*(?=\.[^.]+$)
例如,如果您将匹配项替换为 ***
,结果将是:
j***@e***.com
更新各种屏蔽电子邮件解决方案
foo@bar.com
⇒ f**@b**.com
(当前问题)- s.replaceAll("(?<=.)[^@](?=[^@]*?@)|(?:(?<=@.)|(?!^)\G(?=[^@]*$)).(?=.*\.)", "*")
(参见 the regex demo)
foo@bar.com
⇒ f**@b*r.com
- s.replaceAll("(?<=.)[^@](?=[^@]*?@)|(?:(?<=@.)|(?!^)\G(?=[^@]*$)).(?=.*[^@]\.)", "*")
(参见 the regex demo)
foo@bar.com
⇒ f*o@b*r.com
- s.replaceAll("(?<=.)[^@](?=[^@]*?[^@]@)|(?:(?<=@.)|(?!^)\G(?=[^@]*$)).(?=.*[^@]\.)", "*")
(参见 the regex demo)
foo@bar.com
⇒ f**@b*****m
- s.replaceAll("(?<=.)[^@](?=[^@]*?@)|(?:(?<=@.)|(?!^)\G(?=[^@]*$)).(?!$)", "*")
(参见 the regex demo)
foo@bar.com
⇒ f*o@b*****m
- s.replaceAll("(?<=.)[^@](?=[^@]*[^@]@)|(?:(?<=@.)|(?!^)\G(?=[^@]*$)).(?!$)", "*")
(参见 the regex demo)
原回答
如果您不能使用 基于代码的 解决方案,您可以使用
s.replaceAll("(?<=.)[^@](?=[^@]*?@)|(?:(?<=@.)|(?!^)\G(?=[^@]*$)).(?=.*\.)", "*")
它的作用:
(?<=.)[^@](?=[^@]*?@)
- 除 @
([^@]
) 之外的任何字符,其前面是任何单个字符 ((?<=.)
),后面是任何 0 个或多个字符除了 @
到 @
((?=[^@]*?@)
)
|
- 或
(?:(?<=@.)|(?!^)\G(?=[^@]*$))
- 匹配字符串中以 @
和任何字符 ((?<=@.)
) 或 (|
) 结尾的前一个成功的位置匹配 ((?!^)\G
) 后跟除 @
uo 之外的任何 0+ 个字符到字符串 ((?=[^@]*$)
)
.
- 任何单个字符
(?=.*\.)
- 后跟任何 0+ 个字符,直到字符串中的最后一个 .
符号。
我正在尝试编写一个正则表达式来屏蔽电子邮件地址。示例如下。
input: john.doe@example.en.com
output: j*******@e*********.com
我尝试了以下方法,但似乎无法正常工作。
regex:
(?<=.).(?=[^@]\*?@)
output:j*******@example.en.com
regex:
(?<=.).(?=[^@]\*?)(?=[^\.]\*?\.)
output:j******************.com
如有任何帮助,我们将不胜感激。 demo
如果您不需要具有与原始字符串(更匿名)相同字符数的掩码,这个怎么样:
(?<=^.)[^@]*|(?<=@.).*(?=\.[^.]+$)
例如,如果您将匹配项替换为 ***
,结果将是:
j***@e***.com
更新各种屏蔽电子邮件解决方案
foo@bar.com
⇒f**@b**.com
(当前问题)-s.replaceAll("(?<=.)[^@](?=[^@]*?@)|(?:(?<=@.)|(?!^)\G(?=[^@]*$)).(?=.*\.)", "*")
(参见 the regex demo)foo@bar.com
⇒f**@b*r.com
-s.replaceAll("(?<=.)[^@](?=[^@]*?@)|(?:(?<=@.)|(?!^)\G(?=[^@]*$)).(?=.*[^@]\.)", "*")
(参见 the regex demo)foo@bar.com
⇒f*o@b*r.com
-s.replaceAll("(?<=.)[^@](?=[^@]*?[^@]@)|(?:(?<=@.)|(?!^)\G(?=[^@]*$)).(?=.*[^@]\.)", "*")
(参见 the regex demo)foo@bar.com
⇒f**@b*****m
-s.replaceAll("(?<=.)[^@](?=[^@]*?@)|(?:(?<=@.)|(?!^)\G(?=[^@]*$)).(?!$)", "*")
(参见 the regex demo)foo@bar.com
⇒f*o@b*****m
-s.replaceAll("(?<=.)[^@](?=[^@]*[^@]@)|(?:(?<=@.)|(?!^)\G(?=[^@]*$)).(?!$)", "*")
(参见 the regex demo)
原回答
如果您不能使用 基于代码的 解决方案,您可以使用
s.replaceAll("(?<=.)[^@](?=[^@]*?@)|(?:(?<=@.)|(?!^)\G(?=[^@]*$)).(?=.*\.)", "*")
它的作用:
(?<=.)[^@](?=[^@]*?@)
- 除@
([^@]
) 之外的任何字符,其前面是任何单个字符 ((?<=.)
),后面是任何 0 个或多个字符除了@
到@
((?=[^@]*?@)
)|
- 或(?:(?<=@.)|(?!^)\G(?=[^@]*$))
- 匹配字符串中以@
和任何字符 ((?<=@.)
) 或 (|
) 结尾的前一个成功的位置匹配 ((?!^)\G
) 后跟除@
uo 之外的任何 0+ 个字符到字符串 ((?=[^@]*$)
).
- 任何单个字符(?=.*\.)
- 后跟任何 0+ 个字符,直到字符串中的最后一个.
符号。