1

I want to create a regex for extracting blocks from a text file. The block must be between to known value and contains a specific Word.

What I m using right now is this

  Regex.Matches (fileContent, $"START_BLOCK SOMEWORD[^#]+?END_BLOCK")
                    .OfType<Match> ().Select (m => m.Value).ToList ();

which only returns the matches that start with START_BLOCK and have only one space between the start and SOMEWORD. I know that between the start and the word can be only spaces or control characters.

.....
PRG
PROGRAM PRG
VAR
END_VAR
0A
TRUE
ANDA
TRUE
OR
RESULTd
TEST_F
.....

From this, I want to extract the part beginning with PROGRAM PRG and ending with RESULTd. So the block between PRG and TEST_F and containing(directly after PRG but can contain more than spaces or carriage returns) the Keyword PROGRAM.

Note that the file can contain more than one PROGRAM but every one has a unique name.

3
  • Can you add some examples? Commented Oct 3, 2019 at 14:47
  • 2
    Please refer to the various components you're referring to in a consistent way so people can understand what you're trying to do. Commented Oct 3, 2019 at 14:51
  • edited my question Commented Oct 3, 2019 at 15:01

1 Answer 1

1

You could match the lines that contains PROGRAM and then match until the first occurrence of RESULTd

.*\bPROGRAM\b.*(?:\r?\n(?!RESULTd\b).*)*\r?\nRESULTd\b

Regex demo

If the words PRG and TESTF should be there and there can be one or more whitespace chars \s* after PRG, you can use a capturing group.

PRG\r?\n\s*(PROGRAM\b.*(?:\r?\n(?!RESULTd\b).*)*\r?\nRESULTd)\r?\nTEST_F

Regex demo | C# demo

enter image description here

Your code might look like

string pattern = @"PRG\r?\n\s*(PROGRAM\b.*(?:\r?\n(?!RESULTd\b).*)*\r?\nRESULTd)\r?\nTEST_F";
var items = Regex.Matches(fileContent, pattern)
    .OfType<Match>()
    .Select (m => m.Groups[1].Value)
    .ToList();
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.