Robert Michálek
Robert Michálek

Reputation: 75

C# regex replacement - not able to use matched variables

I am trying to use regex in C# to edit string format.

Previous format is 09/08/2015 or 9/08/2015 and pattern I tried is "([0-9]{1,}|[0-9]{2,})/[0-9]{2,}/[0-9]{4,}" New format should be 2015 08 09

I am trying to use variables from match, but it shows only $1 and not $2 or $3

string pattern = "([0-9]{1,}|[0-9]{2,})/[0-9]{2,}/[0-9]{3,}";
string replacement = "$3 $2 $1";
Regex rgx = new Regex(pattern);
string result = rgx.Replace(text, replacement);
richTextBox1.Text = result;

Please, help me to edit proper pattern format.

EDIT:
I just forget to write, that at first I am loading data from .txt file and in that data I am replacing date format 31/03/2015 or 1/03/02 to 2015 03 31.

Upvotes: 0

Views: 77

Answers (3)

Richard
Richard

Reputation: 109120

Much easier approach is to use .NET's inbuilt parser for dates. This will also ensure that invalid inputs like "99/99/0001" will fail.

DateTime res;

if (DateTime.TryParseExact(input, new [] {"dd/MM/yyyy", "MM/dd/yyyy"}, applicableCultureInfo, DateTimeStyles.None, out res)) {
  return res.ToString("yyyy MM dd");
} else {
  throw InvalidArgumentException("Unsupported date format");
}

Upvotes: 1

Soner Gönül
Soner Gönül

Reputation: 98840

Instead of regex, how about parsing them to DateTime and get their string representation with specific format? (I assumed your 09 is day number)

string s = "9/08/2015";
DateTime dt;
if(DateTime.TryParseExact(s, "d/MM/yyyy", CultureInfo.InvariantCulture,
                          DateTimeStyles.None, out dt))
{
    dt.ToString("yyyy MM dd").Dump(); // 2015 08 09
}

or

string s = "09/08/2015";
DateTime dt;
if(DateTime.TryParseExact(s, "dd/MM/yyyy", CultureInfo.InvariantCulture,
                          DateTimeStyles.None, out dt))
{
    dt.ToString("yyyy MM dd").Dump(); // 2015 08 09
}

Or DateTime.TryParseExact has an overload that takes format part as a string array which you can supply multiple formats.

var formats = new[] {"d/MM/yyyy", "d/MM/yyyy"};
if(DateTime.TryParseExact(s, formats, CultureInfo.InvariantCulture,
                             DateTimeStyles.None, out dt))
{
    dt.ToString("yyyy MM dd").Dump(); // 2015 08 09
}

Upvotes: 4

Sami Kuhmonen
Sami Kuhmonen

Reputation: 31193

Because your regex has only one matching group. A correct one would be ([0-9]{1,2})/([0-9]{2})/([0-9]{4}).

The parentheses are used to mark the groups and you only marked the first one with them. Also your regexp is a bit incorrect, since it would also match 832947928/8237549875923/9999, which probably is not what you need.

In this form, it wants one or two numbers, slash, two numbers, slash and four numbers and does the conversion.

Note that using [0-9]{1,2} will allow invalid dates also, so it's not suitable for validation. Only for this conversion.

Upvotes: 1

Related Questions