简体   繁体   中英

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.

Just use String.Split :

var fields = cont.Split(new[] { " ", "\t" },
                        StringSplitOptions.RemoveEmptyEntries);

Adding StringSplitOptions.RemoveEmptyEntries makes sure that if there are multiple consecutive tabs and/or spaces they will "count as one" when extracting the results.

An alternate option would be to use a regular expression.

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.

(new Regex("\\s+")).Split(yourstring)

http://msdn.microsoft.com/en-us/library/8yttk7sy.aspx

var myText="cont = Gallipelle 04/04/2012 16.03.03 5678";
var splitString=myText.split(" ");

// splitString[1] == Gallipelle 
// splitString[2] ==  04/04/2012
// splitString[3] == 16.03.03 
// splitString[4] == 5678

No. No need to replace it with any other delimiter. You can use String's split function and give 'space' as delimiter character. eg in VB.Net:

Dim value As String() = cont.split(CChar(" "))

this will give you a string array whose values you can access: value(0), value(1) and value(2)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM