C# in MS Visual Studio 2010. I am writing output to a log file as part of some code verification. The debugger shows the groups are getting the proper match, as does the Match output. The only thing that is wrong is the output file and I don’t know why. Here is the output I get from the file, where readline is the input line, Match is the result of a Regex match and Slot/Port are the result of getting values from named groups in the Regex. You can see from the log that the Regex Match matches the input line. The debugger says the Named Groups are working.
readline is: fc1/1 is up
Match is: fc1/1 is
Slot and Port are: 1/1
readline is: fc1/3 is up
Match is: fc1/3 is
Slot and Port are: 1/1
Here is the code that does the match – there is some extra stuff I added just to make it easier to watch in the debugger.
if (RegexExtensions.TryMatch(out InterfaceMatch, trimmed, InterfaceMatchString))
{
SlotNum = Convert.ToInt32(InterfaceMatch.Groups["slot"].Value);
PortNum = Convert.ToInt32(InterfaceMatch.Groups["port"].Value);
string slot = InterfaceMatch.Groups["slot"].Value;
string port = InterfaceMatch.Groups["port"].Value;
// write the value of current incoming readline
CiscoDecodeVariables.swlog.WriteLine(String.Format("readline is: {0}", readline));
// write the value of the current match
CiscoDecodeVariables.swlog.WriteLine(String.Format("Match is: {0}", InterfaceMatch.Value.ToString()));
string slotasstring = SlotNum.ToString();
string portasstring = PortNum.ToString();
// here is the line that writes what the slot and port values are
CiscoDecodeVariables.swlog.WriteLine(String.Format("Slot and Port are: {0}/{0}", slotasstring, portasstring));
CiscoDecodeVariables.swlog.Flush();
//sw.Close();
currPort = ((PortModule)ModuleList[SlotNum]).FCPortList[PortNum - 1];
}
Finally, here is the code for the StreamWriter. I decleared a static class with a static variable so I can use the Streamwriter where I need to.
static public class CiscoDecodeVariables
{
static public string LogFileOutPutPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + @"\\ciscodecodelog.txt";
static public StreamWriter swlog = new StreamWriter(LogFileOutPutPath);
}
Adding the RegEx match pattern in question
string InterfaceMatchString = @”fc(?\d+)/(?\d+) is”;
Also, the RegexExtensions.TryMatch() is a static method that returns true for a successful match and sets the InterfaceMatch instance to the result.
It’s a problem with your format string.
“{0}/{0}” means that you’ll get the result “slotasstring/slotasstring” rather than “slotasstring/portasstring”.