2012-12-18 66 views
0

我需要處理具有類似的語法與降價http://daringfireball.net/projects/markdown/syntax,凡在我的情況下,標題行是類似於線串:蟒蛇代替一個字符少

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

,我需要改變自己的深度,即降低它(或增加),這樣:

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

我的蟒蛇正則表達式的小知識是不夠的,瞭解如何更換一批 的n「=」「s的(N-1)‘=’跡象

+0

如果一行只用一個'='開頭,會怎樣? –

+2

用反向引用替換'=(= +)'。 –

+0

您可以使用捕獲組 – nhahtdh

回答

5

您可以使用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 = 
+0

奇怪...給出s ='==== 6.1.3地球====',使用你的代碼我得到'\ x01 \ x02 \ x01' – alessandro

+0

@alessandro對不起,再試一次。我忘了更換一個原始字符串。 –

+0

是的,就是這樣!謝謝[回到正則表達式,瞭解發生了什麼] – alessandro

0

不需要regexes。我會走的很簡單直接:

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

0

我認爲它可以像替換'=(=+)'\1一樣簡單。

有沒有理由不這樣做?

+0

不,如果您知道輸入中唯一的'='字符是標題,這很棒。但是,如果你的文件還包含帶有(不匹配)=='的代碼片段,那麼你將把所有這些變成'=' –

0

一個簡單的解決方案如何?

lines = ['=== a sample header ===', '===== a deeper header ====='] 
new_lines = [] 
for line in lines: 
    if line.startswith('==') and line.endswith('=='): 
     new_lines.append(line[1:-1]) 

結果:

['== a sample header ==', '==== a deeper header ===='] 

或在一行:

new_lines = [line[1:-1] for line in lines if line.startswith('==') and line.endswith('==')] 

這裏的邏輯是,如果它開始和結尾 '==',那麼它必須至少具有很多,所以當我們移除/修剪每一邊時,我們每邊至少留下'='。

只要每個'行'開始並以'== ....'結尾,並且如果您使用這些標題作爲標題,則它們將會一直工作,只要您將新行刪除。

0

無論是第一頭或第二頭,你可以只使用字符串替換這樣

s = "=== a sample header ===" 
s.replace("= "," ") 
s.replace(" ="," ") 

你也可以應付這樣的

BTW第二集:您還可以使用子re模塊的功能,但它不是必需的

+0

,這將從只有1的頭中刪除'='。相反,你應該使用s.replace (「==」,「=」)和s.replace(「==」,「=」)'使這個方法有效。 –

+1

是markdown語法中實際需要的空間嗎? –