2012-01-19 7 views

答えて

24

を、ここでの例は次のとおりです。

def upper_repl(match): 
    return 'GOO' + match.group(1).upper() + 'GAR' 

そして、それを使用する例:

>>> re.sub(r'foo([a-z]+)bar', upper_repl, 'foobazbar') 
'GOOBAZGAR' 
+2

私はそれが非常に複雑であるにもかかわらず、行う必要があると思います。 –

+0

ブリリアント!時々、私達はちょうどRTFD完全にあるべきである... – Zulu

3

s = 'foohellobar' 
def replfunc(m): 
    return m.groups()[0]+m.groups()[1].upper()+m.groups()[2] 
re.sub('(foo)([a-z]+)(bar)',replfunc,s) 

が出力できます:あなたはこれを行うことができますre.sub()に関数を渡すことができ

'fooHELLObar' 
+0

これは正解です。 – dmvianna

5

このような意味ですか?

>>>x = "foo spam bar" 
>>>re.sub(r'foo ([a-z]+) bar', lambda match: r'foo {} bar'.format(match.group(1).upper()), x) 
'foo SPAM bar' 

参考のため、ここではre.sub(強調鉱山)のドキュメンテーション文字列です。

Return the string obtained by replacing the leftmost non-overlapping occurrences of the pattern in string by the replacement repl. repl can be either a string or a callable; if a string, backslash escapes in it are processed. If it is a callable, it's passed the match object and must return a replacement string to be used.

+0

トレースバック(最も最近のコール最後): ファイル ""、ライン1の ファイル "/usr/lib64/python2.6/re.py" inサブ return _compile(pattern、0).sub(repl、string、count) ファイル ""、行1、 ValueError:フォーマット内の長さゼロのフィールド名 – Lobo

2

すでに置換文字列(テンプレート)を持っている場合、あなたはm.group(1)+...+m.group(2)+...+m.group(3)の冗長性とそれをスワップアウトするに熱心ではないかもしれない...時にはそれがきちんと少し文字列を持っていてうれしいです。

MatchObjectexpand()関数を使用すると、一致するテンプレートをsub()と同じ方法で評価でき、できるだけ多くの元のテンプレートを保持できます。該当する部分にupperを使用できます。

re.sub(r'foo([a-z]+)bar', lambda m: 'GOO' + m.expand('\1GAR').upper()) 

これは上記の例に特に有用ではないであろう、それは複雑な状況を支援しないが、そのようなMACアドレスとして捕捉基のより多くとより長い表現にとってより便利であるかもしれないが完全な置き換えが大文字にされているかどうかを確認したいところで、正規表現を検閲します。 Googleでこの全体でお越しの方のために

1

...

また、繰り返しパターンに一致するようにre.subを使用することができます。たとえば、スペースを含む文字列をcamelCaseに変換することができます。

def to_camelcase(string): 
    string = string[0].lower() + string[1:] # lowercase first 
    return re.sub(
    r'[\s]+(?P<first>[a-z])',    # match spaces followed by \w 
    lambda m: m.group('first').upper(), # get following \w and upper() 
    string) 

to_camelcase('String to convert')   # --> stringToConvert 
関連する問題