Cas Cas - 3 months ago 20
C# Question

Get multiline string of textfile within block of two string using regular expression C#

I have a text file and the following are its contents:

initTest
1234 567 8910
1234 567 8910
endTest

initTest
1234 567 8911
1234 567 8911
endTest

initTest
1234 567 8912
1234 567 8912
endTest


and then I need to get the number of block within "initTest" (there are 3 white space before and after the word) and "endTest" (there are 3 white space before and after the word) and save the element of the block to array X. The result should be,
X[0] = {"1234 567 8910 \n 1234 567 8910"}
and X.length = 3.

I've tried by following code in C# using Regex but the result is none match.

string text = line;
string search = @"(^\s*initTest.*?^\s*endTest)";

MatchCollection matches = Regex.Matches(text, search, RegexOptions.Singleline | RegexOptions.IgnoreCase);

Console.WriteLine("there was {0} matches for '{1}'", matches.Count, search);

Console.ReadLine();


I really appreciate anykind of clue and help. Thankyou very much in advance.

Answer

Use

(?<=initTest)(.|\n)*?(?=endTest)

where

initTest(.|\n)*?endTest

will capture required text but includes initTest and endTest. Using (?<=...) and (?=...) will help to get rid of them.

Demo: https://dotnetfiddle.net/tiXRut

Comments