C# Regex Parsing Or Names

You could match the last occurrence of Print Name: and then match as least as possible of the allowed chars until you encounter the same using a backreference until the end of the string.

Note that \s can also match a newline.

\bPrint\sName:\n(?!Print\sName)(?'guarantor1'[a-zA-Z\s',.&\d\--]+?)(?= $)

See a regex demo and a C# demo.

If there should also be a match without the double naming, the space and the backreference to group 1 can be optional.


See another Regex demo.

Example code

string pattern = @"\bPrint\sName:\r?\n(?!Print\sName)(?'guarantor1'[a-zA-Z\s',.&\d\--]+?)(?= \r?$)";
Regex rgx = new Regex(pattern, RegexOptions.Multiline);
MatchCollection matches = rgx.Matches(fullText);
if (matches.Count > 0)
    string guarantor1 = matches[0].Groups["guarantor1"].Value;


Phillip Moore

Read more here: Source link