Yury Pogrebnyak
Yury Pogrebnyak

Reputation: 4173

Matching Negative Sequence

I want to match text between word1 and first occurrence of word2. What's the best way to do that, considering that text may include newline characters? Is there a pattern like this: (word1)(not word2)*(word2)?

Upvotes: 1

Views: 74

Answers (2)

Henk Holterman
Henk Holterman

Reputation: 273179

You can match them using the SingleLine option:

//use '*' or '*?' depending on what you want for "word1 aaa word2 bbb word2"
string pattern = "word1(.*)word2";  
var m = Regex.Match(text1, pattern, RegexOptions.Singleline);
Console.WriteLine(m.Groups[1]);  // the result

MSDN about SingleLine :

... causes the regular expression engine to treat the input string as if it consists of a single line. It does this by changing the behavior of the period (.) language element so that it matches every character, instead of matching every character except for the newline character \n or \u000A.

Upvotes: 1

Michael Petito
Michael Petito

Reputation: 13161

You could use a lazy quantifier to match as few characters as possible between word1 and word2.

(word1).*?(word2)

See quantifiers topic on MSDN.

Upvotes: 3

Related Questions