RHarris
RHarris

Reputation: 11167

Format strings with Regex

I have some very "messy" strings that come in like this:

I need them converted into something like this:

CP-41-CR-0000722-2018

All three of the above would wind up looking like this.

I was curious if there was a way to accomplish this with RegEx? The format would look something like:

CP-41-CR-(\n{7})-(\n{4}).

Is this something that can be done with RegEx?

Upvotes: 0

Views: 143

Answers (2)

user10216583
user10216583

Reputation:

Yes, that can be done with RegEx as follows:

var patt = @".*?(CR)\s?(\d\d\d)\-?(\d\d\d\d)";

Regex.Matches(txtIn.Text, patt, RegexOptions.Multiline | RegexOptions.IgnoreCase).Cast<Match>()
    .ToList().ForEach(m => 
    Console.WriteLine($"CP-41-{m.Groups[1].Value}0000{m.Groups[2].Value}-{m.Groups[3].Value}"));

Where the txtIn.Text is the input of the messy strings.

Here is a test.

Also the pattern .*?(CR)\s?(\d{3})\-?(\d{4}) will do.

Upvotes: 2

jdweng
jdweng

Reputation: 34421

Try following :

            string[] inputs = {
                                  "CR 722-2018",
                                  "CR7222018",
                                  "-CR 7222018"
                              };
            foreach (string input in inputs)
            {
                string digits = string.Join("", input.Where(x => char.IsDigit(x)));
                string output = string.Format("CP-41-CR-000{0}-{1}", digits.Substring(0, 3), digits.Substring(3));
                Console.WriteLine(output);
            }
            Console.ReadLine();

Upvotes: 1

Related Questions