正则表达式以逃避n#除2#

时间:2016-05-29 12:27:06

标签: regex pcre

我试图覆盖Parsedown的标记,只允许<h2>标题。

什么正则表达式会逃避除<h2>以外的所有标题类型?

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

3 个答案:

答案 0 :(得分:1)

您可以使用此正则表达式

^       #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 #
) 

<强> Regex Demo

正则表达式细分

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

注意

{{1}}

答案 1 :(得分:1)

描述

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

Regular expression visualization

替换为: \$1

此正则表达式将执行以下操作:

  • 匹配一个哈希
  • 匹配3个或更多哈希

实施例

现场演示

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

示例文字

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

样本匹配

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

解释

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
----------------------------------------------------------------------

答案 2 :(得分:1)

使用预测标题,但不是双重哈希:

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