python用少一个字符替换子字符串

2024-04-26 12:26:07 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要处理语法类似于markdownhttp://daringfireball.net/projects/markdown/syntax的行,在我的例子中,头行类似于:

=== a sample header ===
===== a deeper header =====

我需要改变它们的深度,即减少(或增加)深度,以便:

== a sample header ==
==== a deeper header ====

我对python正则表达式所知甚少,不足以理解如何替换数字 带(n-1)'='符号的'=''中的n个


Tags: samplenet语法符号数字例子markdownprojects
3条回答

不需要正则表达式。我会非常简单和直接:

import sys

for line in sys.stdin:
    trimmed = line.strip()
    if len(trimmed) >= 2 and trimmed[0] == '=' and trimmed[-1] == '=':
        print(trimmed[1:-1])
    else:
        print line.rstrip()

开头的strip很有用,因为在降价中,人们有时会在一行的末尾(也可能是开头)留下空格。相应调整以满足您的要求。你知道吗

这是一个live demo。你知道吗

我认为它可以像用\1替换'=(=+)'一样简单。你知道吗

有什么理由不这样做吗?你知道吗

您可以使用backreferences和两个negative lookarounds来查找两组相应的=字符。你知道吗

output = re.sub(r'(?<!=)=(=+)(.*?)=\1(?!=)', r'\1\2\1', input)

如果您有一个较长的字符串包含多个标题(并且将更改所有标题),那么这种方法也会起作用。你知道吗

正则表达式做什么?你知道吗

(?<!=)  # make sure there is no preceding =
=       # match a literal =
(       # start capturing group 1
  =+    # match one or more =
)       # end capturing group 1
(       # start capturing group 2
  .*?   # match zero or more characters, but as few as possible (due to ?)
)       # end capturing group 2
=       # match a =
\1      # match exactly what was matched with group 1 (i.e. the same amount of =)
(?!=)   # make sure there is no trailing =

相关问题 更多 >