Regex - Need to replace a pattern found with a * mask

Hey,

It doesn't matter how I find the pattern I'm interested in, the thing is I want to replace all the chars that belong to the captured text into a mask.

Let's say I'm working on a big message : msg
I would like to catch: the following Regex reg = new Regex("CREDIT CARD:(?<PatternToMask>.*?)")
And replace each character in the result into a new char = *

Thanks,
breezbackAsked:
Who is Participating?
 
iHadiConnect With a Mentor Commented:
Hi breezback

Try the following code in a console application
        static void Main(string[] args)
        {
            string str = ProcessString("CREDIT CARD:ABCD;CREDIT CARD:EFGHhhggfgh");
 
            Console.WriteLine(str);
        }
 
        static string ProcessString(string str)
        {
            MatchCollection matches = Regex.Matches(str, @"CREDIT CARD:(?<PatternToMask>[\w]*)");
            if (matches.Count == 0)
                return "";
 
            for (int i = 0; i < matches.Count; i++)
            {
                int index = matches[i].Groups["PatternToMask"].Index;
                int length = matches[i].Groups["PatternToMask"].Value.Length;
                string tmpstr = "";
 
                tmpstr = tmpstr.PadLeft(length, '*');
 
                str = str.Remove(index,length);
                str = str.Insert(index, tmpstr);
            }
            return str;
        }

Open in new window

0
 
Richard QuadlingSenior Software DeveloperCommented:
I think you are going to have to do this in 2 parts.

The first part is to extract the match, then get the length of the match and then replace it with a new repeated string of *.

You also could use something like this ...

(CREDIT CARD:\**)\d

and repeated replace this with ...

$1*

until there are no more matches.


0
 
breezbackAuthor Commented:
Excellent, do you think it is optimized (my application is speed-critical)?
0
All Courses

From novice to tech pro — start learning today.