3

I’m trying to write a regex substitution for markup-ish text. I try to catch every line that is not empty and does not start with any number of hashtags.

I tried to catch just the content using the negative lookbehind assertion so find lines that start with any number of hashtags followed by a space.

Here is what I tried with a negative lookbehind:

/^(?<!#+ )(.*?)$/i

My searched text looks similar like this:

# heading

## part
Lorem ipsum dolor sit amet
Lorem ipsum dolor sit amet
Lorem ipsum dolor sit amet
Lorem ipsum dolor sit amet
Lorem ipsum dolor sit amet

## part
Lorem ipsum dolor sit amet
Lorem ipsum dolor sit amet
Lorem ipsum dolor sit amet
Lorem ipsum dolor sit amet
Lorem ipsum dolor sit amet

I get the error invalid pattern in look-behind, and I don’t understand it. Could you help me?

rcheetah
  • 37
  • 4
  • 3
    You need a **lookahead**. `/^(?!#+ ).*$/`. – Wiktor Stribiżew Jul 31 '19 at 20:37
  • 1
    The pattern is invalid because you have a variable length in the assertion. Basically a quantifier after the pound sign. Aside from that, if variable length were allowed in Ruby look behind assertions, this type of beginning `^(? –  Jul 31 '19 at 20:44
  • just as @WiktorStribiżew said. Or you can move one character and do a look behind for `#` like /^.(? – JBone Jul 31 '19 at 20:46
  • 2
    Basically the regex you're looking for is this `(?m)^(?!#).*\S.*` which will match any line that does not start with a hash tag and the line must contain at least one non-whitespace character. –  Jul 31 '19 at 20:47
  • 1
    Ah, I see. It’s still a lookahead because it is AFTER the start of a line. That was the bug in my mind. Thank you all for your answers, also the other ones. I think I now understand the concept better. You’re great! – rcheetah Jul 31 '19 at 21:30
  • does /^[^#]+/gmi make sense? – Hamed Ghasempour Aug 01 '19 at 05:04

0 Answers0