Search code examples
c#stringoperation

Need to extract fields from a string in C#


I have extract the 3 usable field from a string. There is no common delimiter, there can be both blank spaces and tabs.

First, what I am doing is replacing all double blanks and tabs by '**'

Given String :

cont = Gallipelle 04/04/2012 16.03.03 5678

I am using:

cont.Replace(" ", "**").Replace(" ", "**").Replace(" ", "**").Replace("**", "").Trim()

The answer becomes:

****** Gallipelle******04/04/2012 16.03.03************************ 5678*****

Is the approach correct? How do I extract the stuffs from here? I just need all the extracts in string datatype.


Solution

  • You can use regex groups to find out three values name, date, number.

    A group is defined as (?<group_name><regex_expr>)

    So you could write

                Regex regex = new Regex("(?<name>(\\S*))(\\s*)(?<date>((\\S*)\\s(\\S*)))(\\s*)(?<number>(\\d*))");
                Match match = regex.Match(yourString);
                if (match.Success)
                {
                    string name = match.Groups["name"].Value;
                    string date = match.Groups["date"].Value;
                    string number = match.Groups["number"].Value;
                }
    

    \s* matches sequence of whitespaces which includes tabs. \S* matches sequence of non-whitespace characters. \d* matches sequence of digits.