2017-10-13 3 views
0

私はthis is title [[this is translated title]]という文字列を持っており、これらの2つのサブフィールドを抽出する必要があります。 this is titlethis is translated title正規表現を使用してPythonで部分文字列を抽出する方法

私は正規表現を使用しようとしましたが、それを完了できませんでした。

def translate(value): 
    # Values are paseed in the form of 
    # "This is text [[This is translated text]]" 
    import re 
    regex = r"(.+)(\[\[.*\]\])" 
    match = re.match(regex, value) 
    # Return text 
    first = match.group(1) 

    # Return translated text 
    second = match.group(2).lstrip("[[").rstrip("]]") 

    return first, second 

しかし、これは失敗します。文字列は「シンプルプレーンテキスト」

+1

あなたが働いていると思われるものを使用してください。どうしたの? – wim

答えて

0

を使用せずに、簡単な方法を見つけますgroup(2)にので、あなたのコードは、これはあなたが期待通りに返し

def translate(value): 
    # value = "This is text [[This is translated text]]" 
    import re 
    regex = r'((\w.*)\[\[(\w.*)\]\]|(\w.*))' 
    match = re.match(regex, value) 
    result = [x for x in match.groups() if x and x!=value] 
    return result if result else value 

でなければなりません。

あなたの正規表現をテストするには、this.

+0

私はこれが値= "これはテキストです" – shining

+0

コードが失敗したと思います。今すぐチェック – Mani

0

あるとき、私はあなたがr'((\w.*)\[\[(\w.*)\]\]|(\w.*))利回りこれはgroup(1)でタイトルで、これはタイトル翻訳される正規表現を使用する必要が正規表現

def trns(value): 
    first, second = value.rstrip("]]").split("[[") 
    return first, second 
関連する問題