正则表达式:用星号Regex替换输入中的最后4个数字

时间:2014-11-26 12:36:13

标签: c# regex automapper

我目前需要在Automapper(C#)中使用Regex表达式提供一些帮助。

我想用符号*替换最后4个(和另一个输入中的2个)数字。现在我只覆盖最后一位数字。

 .AfterMap((from, to) =>
                {
                    if (from.x!= null)
                        to.x= Regex.Replace(from.x, "[0-9]{2}$", "*");
                    if (from.y!= null)
                        to.y= Regex.Replace(from.y, "[0-9]{4}$", "*");
                })

请帮忙!

2 个答案:

答案 0 :(得分:2)

你的正则表达式很好并且符合你想要的。但是,在这两种情况下,您只需插入一个*。使用:

.AfterMap((from, to) =>
            {
                if (from.x!= null)
                    to.x= Regex.Replace(from.x, "[0-9]{2}$", "**");
                if (from.y!= null)
                    to.y= Regex.Replace(from.y, "[0-9]{4}$", "****");
            })

答案 1 :(得分:0)

正如詹姆斯索普注意到的那样,唯一的问题是你的替换字符串。

所以对于挑战:一种模式来统治它们的模式

to.z = Regex.Replace(from.z, "[0-9]{2}(?=(?:[0-9]{2})?$)", "**");