在字符串中使用正则表达式屏蔽最后 4 位数字,但不屏蔽连字符 (-)

问题描述 投票:0回答:1

我需要屏蔽信用卡号中的最后 4 位数字,但不需要屏蔽连字符 (-)。

例如,如果我有一个像“1234-5678-9123-4567-891”这样的字符串,则输出应该是“xxxx-xxxx-xxxx-xxx7-891”。如果我有一个像“1234-5678-9123-4567”这样的字符串,那么输出应该是“xxxx-xxxx-xxxx-4567”,对于像“123456789123”这样的字符串,输出应该是“xxxxxxx9123”。

无论如何,最后 4 位数字应该是可见的。如果是奇数字符串(就像第一个示例一样),则最后 4 位数字(包括连字符)(如果有)应该可见。

谢谢

尝试过以下但并非在所有情况下都有效---

 public static string MaskCreditCardNo(this string value)
 {
     if (string.IsNullOrWhiteSpace(value))
         return value;

     return Regex.Replace(value, "(\\d[\\s|-]?){10,}\\d", match=>
         {
             string CCnumber = match.Value;
             string digits = string.Concat(CCnumber
          .Where(c => char.IsDigit(c)));
             return (digits.Length >= 12 && digits.Length <= 19) ?
             Regex.Replace(CCnumber.Substring(0, CCnumber.Length - 4), @"\d", "x") + CCnumber.Substring(CCnumber.Length - 4) : match.Value;
     });
 }
c# regex
1个回答
0
投票

您可以在匹配数字后使用负先行模式,以确保在字符串末尾之前后面不会跟有 3 个或更少的数字:

Regex.Replace(value, @"\d(?!(?:\D*\d){0,3}\D*$)", "x")
© www.soinside.com 2019 - 2024. All rights reserved.