views:

44

answers:

2

Hello.

I want to split my string s1 = 6/28/2010 4:46:36 PM and s2 = 16:46:36.5013946 . and concatenate them to new s3 = 20010062816463650. But when I split s2. my regex doesn't work. I was paused now.

using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;

namespace ConAppTest
{
    class Program
    {

        static void Main(string[] args)
        {
            string s1 = ""; // date
            string s2 = ""; // time
            Console.WriteLine("{0}", DateTime.Now);
            s1 = DateTime.Now.ToString();
            Console.WriteLine("{0}", DateTime.Now.TimeOfDay);
            s2 = DateTime.Now.TimeOfDay.ToString();

            Regex regex1 = new Regex(@" |:|/");    //6/28/2010 2:19:21 PM
            char[] separators1 = { ' ', '/' };
            foreach (string sub1 in regex1.Split(s1))
            {
                Console.WriteLine("Word1: {0}", sub1);
            }

            Regex regex2 = new Regex(@":|.");  //14:19:21.8771215
            char[] separators2 = { ':', '.' };
            foreach (string sub2 in regex2.Split(s2))
            {
                Console.WriteLine("Word2: {0}", sub2);
            }
        }



    }
}
//output
//6/28/2010 4:46:36 PM
//16:46:36.5013946
//Word1: 6
//Word1: 28
//Word1: 2010
//Word1: 4
//Word1: 46
//Word1: 36
//Word1: PM
//Word2:
//Word2:
//Word2:
//Word2:
//Word2:
//Word2:
//Word2:
//Word2:
//Word2:
//Word2:
//Word2:
//Word2:
//Word2:
//Word2:
//Word2:
//Word2:
//Word2:
+3  A: 

A dot (.) matches any character when used in a regular expression. You need to escape it with a backslash:

Regex regex2 = new Regex(@":|\.");

Note that this is entirely separate from the escaping performed in string literals - it's part of the regular expressions language, not the C# language.

(I would also agree with Oded's suggestion that using a regular expression probably isn't the most appropriate solution here anyway.)

Jon Skeet
@Jon, Thank you.
Nano HE
+4  A: 

Why are you using RegEx at all for this?

Use DateTime.TryParse or DateTime.Parse to parse the input string to a DateTime object (if you need an exact parse, there are also ParseExact and TryParseExact that take a format string).

You can then use DateTime.ToString with a custom format string that will output the exact output you want directly from DateTime objects.

DateTime.ToString("yyyyMMddHHmmssff");
Oded
@Oded, Thanks a lot for teaching me the good solution.
Nano HE