regex to find leading hashes not followed by a space

Viewed 140

I want to fix markdown headers that are missing a space after the hash

valid markdown vs invalid markdown headers


this one is valid:

### CAUSE:  

this one isn't:

###CAUSE:  


I can find valid ones just fine (and ignore invalid ones) with:

^#+\s+ or ^#+[\s]+

The problem when I want negate the space following the hash, i.e. flag all the ones not followed by a space which are invalid markdown.

I've tried @ https://regex101.com/, using the Python flavor.

^#+[^\s]+

However, it IS matching partially, up to the hashes:

### CAUSE:
 matches the 3 hashes

Same problem with ^#+[^ ]+

How do I reject ### CAUSE, entirely but match ###CAUSE?

(note: a simple state machine checks whether I am in a code block, so a #comment in a bash or Python code block isn't a problem).

Also, while regex 101 is doing this, I only used it because this is the behavior I am getting from Python 3.8 itself.

1 Answers

You can make sure the first non-whitespace char is not #:

^#+[^\s#]\S*

See the regex demo

Details

  • ^ - start of string (or line, if re.M option is used)
  • #+ - 1 or more # chars
  • [^\s#] - any char but whitespace and #
  • \S* - zero or more non-whitespace chars.

Actually, you may also achieve it with other regular expressions. Say, you may use a negative lookahead based pattern:

^(?!#+\s)#+\S+

Here, (?!#+\s) would fail the match if there is a whitespace after one or more # chars.

Related