frosty
frosty

Reputation: 2851

Regular expression to escape n # except 2 #

I'm trying to override Parsedown's markup to only allow <h2> headings.

What regex would escape all heading types except <h2>?

#Heading -> \#Heading
##Heading -> ##Heading
###Heading -> \###Heading
####Heading -> \####Heading
#####Heading -> \#####Heading
######Heading -> \######Heading

Upvotes: 0

Views: 56

Answers (3)

rock321987
rock321987

Reputation: 11032

You can use this regex

^(?!##\w)(?=#)

Regex Demo

Regex Breakdown

^       #Start of string
(?!     #Negative lookahead(it means, whatever is there next do not match it)
 ##\w   #Assert that its impossible to match two # followed by a word character
)
(?=     #Positive lookahead
 #      #check if there is at least one #
) 

NOTE

\w denotes any character from [A-Za-z0-9_].
[..] denotes character class. Any character(not string) present in this will be matched.

Upvotes: 1

Ro Yo Mi
Ro Yo Mi

Reputation: 15000

Description

^((?:#|#{3,})[^#])

Regular expression visualization

Replace with: \$1

This regular expression will do the following:

  • match one hash
  • match 3 or more hash

Example

Live Demo

https://regex101.com/r/kE4oK6/1

Sample text

#Heading
##Heading
###Heading
####Heading
#####Heading
######Heading

Sample Matches

\#Heading
##Heading
\###Heading
\####Heading
\#####Heading
\######Heading

Explanation

NODE                     EXPLANATION
----------------------------------------------------------------------
  ^                        the beginning of a "line"
----------------------------------------------------------------------
  (                        group and capture to \1:
----------------------------------------------------------------------
    (?:                      group, but do not capture:
----------------------------------------------------------------------
      #                        '#'
----------------------------------------------------------------------
     |                        OR
----------------------------------------------------------------------
      #{3,}                    '#' (at least 3 times (matching the
                               most amount possible))
----------------------------------------------------------------------
    )                        end of grouping
----------------------------------------------------------------------
    [^#]                     any character except: '#'
----------------------------------------------------------------------
  )                        end of \1
----------------------------------------------------------------------

Upvotes: 1

Bohemian
Bohemian

Reputation: 424993

Use look aheads for headings, but not double hashes:

 ^(?!##\w)(?=#+)

Upvotes: 1

Related Questions