Lazy Regex Match in .NET. What is wrong here?

In the following example, I would like to get the text between pMAINp and first pMDSp. The regular expression has the appearance and forecast:

string contents = "pMAINp MAP B FlightTest Load pMDSp ZutiCarrier pWingp some pMDSp more pWingp end";
string blockMainRegex = @"(?<=pMAINp)[\s\w+]+(?=(pMDS)?)";

As a result, I was hoping: "Download MAP B FlightTest"

but it returns: "MAP B FlightTest Download pMDSp ZutiCarrier pWingp pFDSp more pWingp end"

You will notice that I am trying to find a lazy match here: (pMDS)? which is clearly not working! Any help with this would be greatly appreciated. Thank you. :-)

EDIT : Oops, the search text has been fixed.

This works fine:
  string blockMainRegex = @ "(? <= PMAINp) [\ s \ w +] +? (? = PMDS)";

+3
source share
2 answers

You will notice that I am trying to find a lazy match here: (pMDS)? which is clearly not working!

You seem to misunderstand how lazy-matching works.

Do you apply the lazy operator to the quantifier - *, + ,? etc. - elsewhere, it is interpreted as zero-one.

If you want one part of the regular expression to match as few characters as possible, apply the lazy operator to the quantifier associated with this part of the regular expression - in this case you want to use it like this:

[\s\w+]+?
+3
source
string blockMainRegex = @"pMAINp(.*?)pMDSp";

The first group will have what you want. For instance:.

Regex re = new Regex(@"pMAINp(.*?)pMDSp");
string result = re.Match(contents).Groups[1].ToString();
+1
source

Source: https://habr.com/ru/post/1752021/