Fun with C# and Regular Expressions

Hey guys,

I’m currently fighting with regular expressions in C# and I just can’t see what I’m doing wrong.
I get a list of Devices from an external program (adb.exe) which looks like this:

List of devices attached 
R32D102RVQH	device
HT13WTJ33998	device

My goal is to get an array containing only [R32D102RVQH, HT13WTJ33998]. So I’m filtering the string using a Regex, like this:

Devices = new List<Device>();
            string cmdRtn = Program.ExecuteCommand("adb.exe", "devices", false);
            Regex re = new Regex(@"^(.+?)\s+?device$", RegexOptions.Multiline);
            MatchCollection mc = re.Matches(cmdRtn);
            foreach (Match m in mc)
            {
                string test = m.Groups[0].Value;
                Console.Write(test);
            }

But no matter what I do, C# doesn’t return the correct values (the example above returns a group containing the string “List of devices attached R32D102RVQH deviceHT13WTJ33998 device”).
The worst thing is that I’ve tested my Regex on many different tools using the same pattern, text, and options and it worked every single time :S.
I’m sure that I’m doing something wrong but the more I try, the more C# regex look like voodoo magic, so if there is a wizard around, I’ll gladly welcome his help :).

Cheers!

link here to a dot net regex tester, which should have the same quirks as C#:

Testing yours I think this is what you want:

^(\w+)\W+(device)

Thanks Theodox, it does seem to do the trick indeed. I’ll test that in my code asap and I’ll let you know the results :).

EDIT: I’ve tested your pattern in my code and it works after a small modification: I had to use “(\w+)\W+(device)” instead of “^(\w+)\W+(device)” for some reason. Case solved :slight_smile: