Python--Pythonでre.sub

14886 ワード

定義:
re.sub(pattern, repl, string, count=0, flags=0)

Return the string obtained by replacing the leftmost non-overlapping occurrences of pattern in string by the replacement repl. If the pattern isn’t found, string is returned unchanged. repl can be a string or a function; if it is a string, any backslash escapes in it are processed. That is, 
is converted to a single newline character, \r is converted to a carriage return, and so forth. Unknown escapes such as \j are left alone. Backreferences, such as \6, are replaced with the substring matched by group 6 in the pattern. For example: >>> re.sub(r'def\s+([a-zA-Z_][a-zA-Z_0-9]*)\s*\(\s*\):', ... r'static PyObject*
py_\1(void)
{', ... 'def myfunc():') 'static PyObject*
py_myfunc(void)
{' If repl is a function, it is called for every non-overlapping occurrence of pattern. The function takes a single match object argument, and returns the replacement string. For example: >>> def dashrepl(matchobj): ... if matchobj.group(0) == '-': return ' ' ... else: return '-' >>> re.sub('-{1,2}', dashrepl, 'pro----gram-files') 'pro--gram files' >>> re.sub(r'\sAND\s', ' & ', 'Baked Beans And Spam', flags=re.IGNORECASE) 'Baked Beans & Spam' The pattern may be a string or an RE object. The optional argument count is the maximum number of pattern occurrences to be replaced; count must be a non-negative integer. If omitted or zero, all occurrences will be replaced. Empty matches for the pattern are replaced only when not adjacent to a previous match, so sub('x*', '-', 'abc') returns '-a-b-c-'. In addition to character escapes and backreferences as described above, \g<name> will use the substring matched by the group named name, as defined by the (?P<name>...) syntax. \g<number> uses the corresponding group number; \g<2> is therefore equivalent to \2, but isn’t ambiguous in a replacement such as \g<2>0. \20 would be interpreted as a reference to group 20, not a reference to group 2 followed by the literal character '0'. The backreference \g<0> substitutes in the entire substring matched by the RE. Changed in version 2.7: Added the optional flags argument.

re.subの機能
reはregular expressionの書いたもので、正規表現を表す.
subはsubstituteの書いたもので、置換を表す.
re.subは正規表現の面での関数であり、正規表現を通じて、普通の文字列のreplaceよりも強力な置換機能を実現するために使用される.
最も簡単な例を挙げます.
入力文字列が次の場合:
inputStr = "hello 111 world 111"

では、あなたは
replacedStr = inputStr.replace("111", "222")

取り替える
"hello 222 world 222"

ただし、文字列を入力すると次のようになります.
inputStr = "hello 123 world 456"

123と456を222に変えたいのです
(他にもっと複雑な状況がある場合)、
文字列のreplaceで直接この目的を達成することはできません.
reを借りる必要がある.subは、正規表現によって、このような比較的複雑な文字列の置換を実現する.
replacedStr = re.sub("\d+", "222", inputStr)

もちろん、実際の状況では、この例よりも複雑なものがあり、その他の様々な特殊な状況では、このreを通過するしかない.subはこのような複雑な置換機能を実現した.
だから、re.subの意味、作用、機能は:
入力した文字列について、正規表現(の強力な文字列処理機能)を使用して、(比較的複雑な)文字列置換処理を実現し、置換された文字列を返します.
そのうちre.subはまた、countが置換する個数を指定するなど、さまざまなパラメータをサポートします.
以下、各パラメータの意味を詳細に説明する.
re.subの各パラメータの詳細な説明
re.subには5つのパラメータがあります.
re.sub(pattern, repl, string, count=0, flags=0)
3つの必須パラメータ:pattern,repl,string
2つのオプションパラメータ:count,flags
最初のパラメータ:pattern
patternは、正規のパターン文字列を表し、これはあまり説明されていません.
必要なのは、
  • 反スラッシュに数字(N)を加えると、マッチングに対応するグループ(matched group)例えば6は、マッチング前のpatternの6番目のグループを意味し、patternの中で、前には必ず対応していることを意味し、6番目のグループは、その後も
  • を参照することができます.
    たとえば、次のように処理します.
    hello crifan, nihao crifan

    そしてここの、前後のcrifanは、きっと同じに違いない.
    このような文字列全体をcrifanliに変えたいのです
    このようなre.sub実装の置き換え:
    inputStr = "hello crifan, nihao crifan";
    replacedStr = re.sub(r"hello (\w+), nihao \1", "crifanli", inputStr);

    2番目のパラメータ:repl
    replとは、replacement、置き換えられた文字列の意味です.
    replは文字列であっても関数であってもよい.
    replは文字列です
    replが文字列であれば、その中の任意の反スラッシュエスケープ文字が処理されます.
    次のようになります.
  • :対応する改行文字として処理されます.
  • r:リターン記号として処理されます.
  • その他認識できない遷移文字は、普通の文字として認識されるだけである:例えばjは、jというアルファベット自体として処理される.
  • スラッシュにgと中括弧の中の1つの名前、すなわち:g、名前を付けたグループに対応して、named group
  • 次に、上記の例を示します.
    対応したい:
    hello crifan, nihao crifan

    のcrifanが抽出され、残りは:
    crifan
    次のように書くことができます.
    inputStr = "hello crifan, nihao crifan";
    replacedStr = re.sub(r"hello (\w+), nihao \1", "\g<1>", inputStr);
    print "replacedStr=",replacedStr; #crifan

    対応する名前付きグループのバージョンは、次のとおりです.
    inputStr = “hello crifan, nihao crifan”; replacedStr = re.sub(r”hello (?P\w+), nihao (?P=name)”, “\g”, inputStr); print “replacedStr=”,replacedStr; #crifan
    replは関数です
    例:
    たとえば、次のように入力します.
    hello 123 world 456

    その中の数字の部分を111を加えて、次のようにします.
    hello 234 world 567

    では、次のように書くことができます.
    #!/usr/bin/python
    # -*- coding: utf-8 -*-
    
    import re;
    
    def pythonReSubDemo():
        """
            demo Pyton re.sub
        """
        inputStr = "hello 123 world 456";
    
        def _add111(matched):
            intStr = matched.group("number"); #123
            intValue = int(intStr);
            addedValue = intValue + 111; #234
            addedValueStr = str(addedValue);
            return addedValueStr;
    
        replacedStr = re.sub("(?P\d+)", _add111, inputStr);
        print "replacedStr=",replacedStr; #hello 234 world 567
    
    ###############################################################################
    if __name__=="__main__":
        pythonReSubDemo();

    3番目のパラメータ:string
    stringとは、処理され、置き換えられるstring文字列を表す.
    特に説明することはありません.
    4番目のパラメータ:count
    例:
    前の例に続き、一致したコンテンツについては、その一部のみが処理される.
    たとえば、
    hello 123 world 456 nihao 789

    前の2つの数字:123456を処理するように、789ではなく111を追加します.
    では、次のように書くことができます.
    #!/usr/bin/python
    # -*- coding: utf-8 -*-
    
    import re;
    
    def pythonReSubDemo():
        """
            demo Pyton re.sub
        """
        inputStr = "hello 123 world 456 nihao 789";
    
        def _add111(matched):
            intStr = matched.group("number"); #123
            intValue = int(intStr);
            addedValue = intValue + 111; #234
            addedValueStr = str(addedValue);
            return addedValueStr;
    
        replacedStr = re.sub("(?P\d+)", _add111, inputStr, 2);
        print "replacedStr=",replacedStr; #hello 234 world 567 nihao 789
    
    ###############################################################################
    if __name__=="__main__":
        pythonReSubDemo();

    5番目のパラメータ:flags
    reについてsubの注意事項
    置換された文字列、すなわちパラメータreplは、通常の文字列であり、patternではないことに注意してください.
    文法は次のとおりです.
    re.sub(pattern, repl, string, count=0, flags=0)

    すなわち、対応する2番目のパラメータはreplである.
    対応するr接頭辞を指定する必要があります.patternです.
    r"xxxx"

    4番目のパラメータflagの値を誤って3番目のパラメータcountに渡さないでください
    さもないと私のところに現れます.
    【解決済み】Python中、(1)re.compileの後でsubは仕事ができますが、re.subが働かない、あるいは(2)re.search後replaceは動作するが、直接re.subおよびre.後でsubは働かない
    問題:
    3番目のパラメータを渡すとflagの値は、
    結果は実際にcountの値です
    だからre.subは機能しません.
    パラメータを明確に指定します.
    replacedStr = re.sub(replacePattern, orignialStr, replacedPartStr, flags=re.I); # can omit count parameter

    または、
    replacedStr = re.sub(replacePattern, orignialStr, replacedPartStr, 1, re.I); # must designate count parameter

    正常に動作します.