tags:

views:

41

answers:

2

Using regex (in c#.net) is it possible to check the previous line of a string?

For instance, I need to select strings in which the previous line is not a series of asterisks (prev line:******)

+1  A: 

You can use RegexOptions.MultiLine and then match something like the following:

(?<!^\*+$\r?\n?.*)foo

This matches "foo" only if the previous line doesn't consist of asterisks.

Joey
+4  A: 
(?m)^(?<!^\*+\r?\n).+

(?m) turns on multiline mode so ^ can match the beginning of a line. The lookbehind checks the previous line; if it succeeds (that is, it doesn't see a line of asterisks), .+ consumes the current line.

Alan Moore
+1 for actually explaining the regex.
exhuma
Old Macs use just `\r` for a newline. Perhaps the `\n` should be optional?
Jeremy Stein
They can't both be optional; to match exactly one of any of the three kinds of separator you need something like `\r?\n|\r`. I suppose we should keep doing it that way, but I hardly ever saw `\r` in the wild even before they made the switch.
Alan Moore
Oh, I didn't look at your regex closely enough. They could both be optional if they followed a `$`. So something like this: `$\r?\n?`. But you're right, that is a pretty obscure case.
Jeremy Stein