Link to home
Start Free TrialLog in
Avatar of orion7999
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.
SOLUTION
Avatar of Ravi Singh
Ravi Singh
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of orion7999
orion7999

ASKER

hi...sxyz_1234 is a variable. It can keep changing. I tried this. it didnt work.

string ipexp = @"service " + osm.ServiceName + @"\s*ip\saddress\s*(?<ig>\d+\.\d+\.\d+.\d+)";
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\saddress\s*(?<ig>\d+\.\d+\.\d+.\d+)", RegexOptions.Multiline);
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.

Avatar of Fernando Soto
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
What version of .Net framework are you using?
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
this worked. great thanks.
Not a problem, glad I was able to help. ;=)