2

これは簡単な問題のように思えますが、明らかに私が見逃していることがあります。

カスタムタグ間で発生するコードのチャンクをHTML形式のコードに置き換えるように設計されたPython関数があります。

def subCode(text):
    tags = re.findall('<<<mytag>>>.+?<<</mytag>>>', text, re.S)
    for tag in tags:
        match = re.search('>>>(.+?)<<<', tag, re.S)
        replaced_code = replaceCode(match.group(1))
        text = re.sub(tag, replaced_code, text, re.S|re.M)
    return text

これは、次のように、タグの間にあるコードと一致します。

this is some 
random text
<<<mytag>>>now this
   is some
   random code<<</mytag>>>
and this is text again

ただし、コードをフォーマットされた置換に置き換えるわけではなく、返される文字列は入力と同じです。私は何が欠けていますか?

4

1 に答える 1

4

re.sub()2番目の引数として関数をとるそのバリアントを使用したいと思います。これははるかに簡単です。

def subCode(text):
    return re.sub('<<<mytag>>>(.+?)<<</mytag>>>', replaceFunc, text, flags=re.S)

def replaceFunc(match):
    return replaceCode(match.group(1))

の2番目の引数re.sub()が関数の場合、入力として一致オブジェクトを受け取り、置換文字列を返すことが期待されます。

于 2012-11-12T22:23:38.410 に答える