TheSpy
TheSpy

Reputation: 265

Extract part of string from a string?

Hi i am having a problem with my application i want a part of string from a string.The situation is i am having a string variable named as stringData it stores following values:

IP Address         Hardware Address         Lease expiration                Type
192.168.1.2        00-23-8B-87-9A-6B        Mon Jan 02 01:14:00 2006        Dynamic
192.168.1.3        F8-F7-D3-00-03-80        Mon Jan 02 01:14:00 2006        Dynamic 
192.168.1.4        F8-F7-D3-00-9C-C4        Mon Jan 02 01:14:00 2006        Dynamic 
192.168.1.5        F0-DE-F1-33-9C-C4        Mon Jan 02 01:14:00 2006        Dynamic 

I just want Hardware Address starting with F8-F7-D3-00. I am using a substring method now but i am getting only one matched hardware address but there might be a possibility of multiple strings as in above e.g and i want all of them.I am using C#. Any help would be highly appreciable.

Upvotes: 1

Views: 211

Answers (4)

Sabuj Hassan
Sabuj Hassan

Reputation: 39355

Try this one:

string pattern = @"(F8-F7-D3-00\S+)";
string input = "IP Address         Hardware Address         Lease expiration                Type\n"+
    "192.168.1.2        00-23-8B-87-9A-6B        Mon Jan 02 01:14:00 2006        Dynamic\n"+
    "192.168.1.3        F8-F7-D3-00-03-80        Mon Jan 02 01:14:00 2006        Dynamic \n"+
    "192.168.1.4        F8-F7-D3-00-9C-C4        Mon Jan 02 01:14:00 2006        Dynamic \n"+
    "192.168.1.5        F0-DE-F1-33-9C-C4        Mon Jan 02 01:14:00 2006        Dynamic";

MatchCollection matches = Regex.Matches(input, pattern);
foreach (Match match in matches)
{
   Console.WriteLine("Hardware Address: {0}", match.Groups[1].Value);
}

Upvotes: 1

bkardol
bkardol

Reputation: 1268

If the string contains tabs you could split it by '/t' (a horizontal tab).

string hardwareAddresses = stringData.split('/t').ToList().Where((item, index) => index % 4 == 1);

hardwareAddresses will then contain an array of hardware addresses

Upvotes: 0

Michael Mairegger
Michael Mairegger

Reputation: 7301

You can easily use Regular expression

var file = File.ReadAllText(@"....\Input.txt");

Regex r = new Regex("F8-F7-D3-00(-[0-9A-F]{2}){2}");
var matches = r.Matches(file);
foreach (Match m in matches)
{
    Console.WriteLine(m.Value);
}

Upvotes: 0

TaW
TaW

Reputation: 54433

Split the string into separate lines first like this:

        string[] linesep = new string[] {"\r\n"};
        string[] dataLines = stringData .Split(linesep, StringSplitOptions.RemoveEmptyEntries);

Then apply your Substring method to each:

foreach (line in dataLines)
{
    if (line.Contains(yourIPstring)
    // .. do your stuff
}

You may have to change the line separators.

Upvotes: 0

Related Questions