C#C
C#9mo ago
yourFriend

✅ Need help with regular expression pattern

I am trying to match everything between two given tags using regular expression. For example:
string s = "We are living in a <upcase>yellow submarine</upcase>. We don't have <upcase>anything</upcase> else.";
string startTag = "<upcase>";
string endTag = "</upcase>";

// I want it to match:
// 1. <upcase>yellow submarine</upcase>
// 2. <upcase>anything</upcase>

// This pattern match nothing
string pattern = $@"(?'startTag'\s*{startTag})" + $@"(?'text'.*(?!{endTag}))" + $@"(?'endTag'{endTag})";

// This pattern match till last endTag instead for first endTag after the startTag:
// 1. <upcase>yellow submarine</upcase>. We don't have <upcase>anything</upcase>
string pattern = $@"(?'startTag'\s*{startTag})" + $@"(?'text'.*)" + $@"(?'endTag'{endTag})";

MatchCollection matches = Regex.Matches(s, pattern);
Was this page helpful?