orion7999
asked on
C# Regular expression for matching text across multiple lines
I have the following text that i need to parse.
service xyz_1234
ip address 111.111.111.111
protocol tcp
port 0000
active
I need to match
service xyz_1234
ip address 111.111.111.111
with a regular expression
I am having problem as the IP address is on a newline.
HEre is the regular expression I tried. It didnt work.
Regex.Match(str, @"service xyz_1234\s*\r\r\s*ip address\s*(?<ig>\w+\.\w+\. \w+\.\w+)" );
Please let me know where I am going wrong.
service xyz_1234
ip address 111.111.111.111
protocol tcp
port 0000
active
I need to match
service xyz_1234
ip address 111.111.111.111
with a regular expression
I am having problem as the IP address is on a newline.
HEre is the regular expression I tried. It didnt work.
Regex.Match(str, @"service xyz_1234\s*\r\r\s*ip address\s*(?<ig>\w+\.\w+\.
Please let me know where I am going wrong.
SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
hi it works now...but i have a case when IP address need not be in the next line. The text could be in this format.
service xyz_1234
protocol tcp
port 0000
active
ip address 111.111.111.111
The regular expression you gave does not match in these cases.
service xyz_1234
protocol tcp
port 0000
active
ip address 111.111.111.111
The regular expression you gave does not match in these cases.
Hi orion7999;
Try this it will work for you.
string input = "service xyz_1234\n ip address 111.111.111.111\n\n protocol tcp\n\n port 0000\n\n active";
string service = "";
string ip = "";
Match m = Regex.Match(input, @"service\s+(?<Service>\w+ _\d+).*?ip \s+address \s+(?<IP>\ d+\.\d+\.\ d+\.\d+)",
RegexOptions.Singleline | RegexOptions.IgnoreCase);
if( m.Success )
{
service = m.Groups["Service"].Value;
ip = m.Groups["IP"].Value;
}
Fernando
Try this it will work for you.
string input = "service xyz_1234\n ip address 111.111.111.111\n\n protocol tcp\n\n port 0000\n\n active";
string service = "";
string ip = "";
Match m = Regex.Match(input, @"service\s+(?<Service>\w+
RegexOptions.Singleline | RegexOptions.IgnoreCase);
if( m.Success )
{
service = m.Groups["Service"].Value;
ip = m.Groups["IP"].Value;
}
Fernando
What version of .Net framework are you using?
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
this worked. great thanks.
Not a problem, glad I was able to help. ;=)
ASKER
string ipexp = @"service " + osm.ServiceName + @"\s*ip\saddress\s*(?<ig>\
Match ipmatch = Regex.Match(str, ipexp, RegexOptions.Multiline);
I tried matching your statement directly like below too. It does not find the match.
Match ipmatch = Regex.Match(str, @"service\sxyz_1234\s*ip\s