tags:

views:

82

answers:

2

im trying to learn about regex, and how to use it braking up som logs and populating som textboxes with the results.

if i have a simple line like this

Port status: tro-S-02-av1 0/23

and want to put the tro-S-02-av1 and the 0/23 in a variable

all names wold end on av1 so the regular exspression shold be based on this.

i was thinking like this to try to get the string of tro-S-02-av1 to become the value a text box but i cant get it right, how can i do this.

    Regex r;
    Match m;

    r = new Regex("$`\av1");
    m = r.Match("Port status: tro-S-02-av1 0/23");

    nodetbx.Text = m.Value;
+2  A: 

Using groups with the following regex (for example, you could probably clean this up)

Port status: (?<ID>[\d\w\-]+)\s(?<ID2>[\s\S]+)

Will give you two named groups, ID1 and ID2 you can then populate.

I found using named groups easier when first learning regex so you can really see what's going on.

Take a look at nregex to help practice and test regexs too.

    regex r = new regex("Port status: (?<ID>[\d\w\-]+)\s(?<ID2>[\s\S]+)");
    matchcollection mc = r.matches(MyText);
    foreach (match m in mc) {
        string ID1 = m.groups("ID1");
        string ID2 = m.groups("ID2");
    }

Where MyText is either each line looping through the file with ReadLine or the whole file if not too big.

You can then use ID1 and ID2 (renamed to something meaningful) to populate textbox or whatever.

Justin Wignall
great help, that site looks good, but that line just made it so more confusing for me, how do i use ID and ID2?
Darkmage
Depending on if you are processing line by line or as a batch you would loop through each match in the collection and then get the group from each match.I don;t do much c# so can't write the code perfect off the top of my head but... regex r = new regex("REGEX"); matchcollection mc = r.matches(MyText); foreach (match m in mc) { string ID1 = m.groups("ID1"); string ID2 = m.groups("ID2"); }
Justin Wignall
great help :) thank you
Darkmage
+1  A: 

For this particular item you could use the Split string method

string[] words = s.Split(' ');

use the 2nd and 3rd value in the arraylist.

Rickjaah
yes good point but its just a sample the final log is hundreds of lines large, with diffrent info
Darkmage
Then it's indeed useless :)
Rickjaah
True this example would work with splitting the string and would break for exactly the same reasons as the regex example above, it really depends on what range of possible values you expect to see - will the spaces always be in the same place etc.If teh format will always be as above, keep it simple with strings, if it will/might change - regex probably your best bet.
Justin Wignall