tags:

views:

51

answers:

3

Here is the data source, lines stored in a txt file:

servers[i]=["name1", type1, location3];
servers[i]=["name2", type2, location3];
servers[i]=["name3", type1, location7];

Here is my code:

    string servers = File.ReadAllText("servers.txt");
    string pattern = "^servers[i]=[\"(?<name>.*)\", (.*), (?<location>.*)];$";

    Regex reg = new Regex(pattern, RegexOptions.IgnoreCase | RegexOptions.Multiline);
    Match m;

    for (m = reg.Match(servers); m.Success; m = m.NextMatch()) {
        string name = m.Groups["name"].Value;
        string location = m.Groups["location"].Value;                
    }

No lines are matching. What am I doing wrong?

A: 

try this

string pattern = "servers[i]=[\"(?<name>.*)\", (.*), (?<location>.*)];$";
Olexandr
A: 

I don't know if C# regex's are the same as perl, but if so, you probably want to escape the [ and ] characters. Also, there are extra characters in there. Try this:

string pattern = "^servers\[i\]=\[\"(?<name>.*)\", (.*), (?<location>.*)\];$";

Edited to add: After wondering why my answer was downvoted and then looking at Val's answer, I realized that the "extra characters" were there for a reason. They are what perl calls "named capture buffers", which I have never used but the original code fragment does. I have updated my answer to include them.

Graeme Perrow
That was part of it, was matching one line after those changes. Removing the ^ and $ took care of the rest. Thanks!
Jim
+2  A: 

If you don't care about anything except the servername and location, you don't need to specify the rest of the input in your regex. That lets you avoid having to escape the brackets, as Graeme correctly points out. Try something like:

string pattern = "\"(?<name>.+)\".+\s(?<location>[^ ]+)];$"

That's

\"           = quote mark, 
(?<name>     = start capture group 'name', 
.+           = match one or more chars (could use \w+ here for 1+ word chars)
)            = end the capture group
\"           = ending quote mark
.+\s         = one or more chars, ending with a space
(?<location> = start capture group 'location',
[^ ]+        = one or more non-space chars
)            = end the capture group
];$          = immediately followed by ]; and end of string

I tested this using your sample data in Rad Software's free Regex Designer, which uses the .NET regex engine.

Val