Python 3正規表現(二)reモジュール

15959 ワード

Python 3正規表現(一)基本文法規則に正規表現の基本規則が記録されています.次にpythonで正規表現を利用して文字列、すなわちreモジュールでの機能関数の使用をマッチングする方法を書きます.使用時にreモジュールをインポートするには:import re
一、reモジュールでよく使われる関数
1.compile()
ソースの説明:
def compile(pattern, flags=0):
    "Compile a regular expression pattern, returning a pattern object."
    #            ,    Regex  
    return _compile(pattern, flags)

パラメータの説明:
pattern:      
flags:               ,               (iLmsux)    ,      

サンプルコード:
pattern = re.compile(r"\d")
result = pattern.match("123")
print(result.group())
#      1         \d           

pattern = re.compile(r"abc d", re.I|re.X)
result = pattern.match("AbcD")
print(result.group())
#      AbcD             

2.match()
ソースの説明:
1. def match(pattern, string, flags=0):
    """Try to apply the pattern at the start of the string, returning a match object, or None if no match was found."""
    #          pattern,  Match    ,           ,  None。
    return _compile(pattern, flags).match(string)

2. def match(self, string, pos=0, endpos=-1):
    """Matches zero | more characters at the beginning of the string."""
    pass
    #               

パラメータの説明:
#        compile()       
string:         
pos:0
endpos:       ,  -1

サンプルコード:
result = re.match(r"a+\d", "aA123", re.I)
print(result.group())
#      aA1   pattern    ,     ,            

pattern = re.compile(r"abc d", re.I|re.X)
result = pattern.match("0AbcD5", 1, 5)
print(result.group())
#      AbcD   1     ,  5         

3.search()
ソースの説明:
1. def search(pattern, string, flags=0):
    """Scan through string looking for a match to the pattern, returning a match object, or None if no match was found."""
    #      match    ,       search            , match       (pos)         
    return _compile(pattern, flags).search(string)

2. def search(self, string, pos=0, endpos=-1):
    """Scan through string looking for a match, and return a corresponding match instance. Return None if no position in the string matches."""
    pass
    #               

パラメータの説明:
#  match    

サンプルコード:
pattern = re.compile(r"abc d", re.I|re.X)
result = pattern.search("0A2aBcd7")
print(result.group())
#      aBcd                    

pattern = re.compile(r"abc d", re.I|re.X)
matchResult = pattern.match("0AbcD5")
searchResult = pattern.search("0AbcD5")
# matchResult    None
# searchResult.group()      AbcD 
#    pattern       a,             0,  match          

4.group()、groups()、groupdict()
ソースの説明:
1.def group(self, *args):
   """Return one or more subgroups of the match."""
   #               
   pass

2.def groups(self, default=None):
   """Return a tuple containing all the subgroups of the match, from 1 up to however many groups are in the pattern."""
   #                   
   pass

3.def groupdict(self, default=None):
   """Return a dictionary containing all the named subgroups of the match,keyed by the subgroup name."""
   #                   
   pass

パラメータの説明:
group  *args:        ,       ;       ,          。        ,   0  ,         。
groups  default:                  ,      None
groupdict  default:                  ,      None

サンプルコード:
pattern = re.compile(r"([\w]+) ([\w]+)")
m = pattern.match("Hello World Hi Python")
print(m.group())
#      Hello World           Hello        World           
print(m.group(1))
#      Hello            Hello
print(m.group(2))
#      World            World 

pattern = re.compile(r"([\w]+)\.?([\w]+)?")
m = pattern.match("Hello")
print(m.groups())
#      ('Hello', None)               Hello,            ,    None
print(m.groups("Python"))
#      ('Hello', 'Python')             ,     groups       

pattern = re.compile(r"(?P\w+) (?P\w+)")
m = pattern.match("Hello Python")
print(m.groupdict())
#      {'first_name': 'Hello', 'last_name': 'Python'}        groups    

5.findall()
ソースの説明:
def findall(self, string, pos=0, endpos=-1):
   """Return a list of all non-overlapping matches of pattern in string."""
   #                   ,
   #  :        ,  group  
   pass

パラメータの説明:
#  match    

サンプルコード:
pattern = re.compile(r'\d+')
m = pattern.findall('a1b2c33d4')
print(m)
#   ['1', '2', '33', '4']             

m = pattern.findall('a1b2c33d4', 1, 6)
print(m)
#   ['1', '2', '3']  "1b2c3"   

6.finditer()
ソースの説明:
def finditer(self, string, pos=0, endpos=-1):
   """Return an iterator over all non-overlapping matches for the pattern in string. For each match, the iterator returns a match object."""
   #                    
   pass

パラメータの説明:
#  match    

サンプルコード:
pattern = re.compile(r'\d+')
m = pattern.finditer('a1b2c33d4')
print(m)
#      

print(next(m).group())
#           

7.finditer()
ソースの説明:
def split(self, string, maxsplit=0):
   """Split string by the occurrences of pattern."""
   #                      
   pass

パラメータの説明:
maxsplit:         ,        。

サンプルコード:
pattern = re.compile(r'\d+')
m = pattern.split('a1b2c3d4e')
print(m)
#   ['a', 'b', 'c', 'd', 'e']     ,    

m = pattern.split('a1b2c3d4e', 3)
print(m)
#   ['a', 'b', 'c', 'd4e']      ,        

8.split()
ソースの説明:
def split(self, string, maxsplit=0):
   """Split string by the occurrences of pattern."""
   #                      
   pass

パラメータの説明:
maxsplit:         ,        。

サンプルコード:
pattern = re.compile(r'\d+')
m = pattern.split('a1b2c3d4e')
print(m)
#   ['a', 'b', 'c', 'd', 'e']     ,    

m = pattern.split('a1b2c3d4e', 3)
print(m)
#   ['a', 'b', 'c', 'd4e']      ,        

9.sub()
ソースの説明:
def sub(self, repl, string, count=0):
   """Return the string obtained by replacing the leftmost non-overlapping occurrences of pattern in string by the replacement repl."""
   # repl             ,         
   pass

パラメータの説明:
repl:     
string:     
count:     ,      

サンプルコード:
pattern = re.compile(r'\s+')
text = "Process finished with exit code 0"
m = pattern.sub('-', text, 3)
print(m)
#     Process-finished-with-exit code 0       ‘-’   

10.subn()
ソースの説明:
def subn(self, repl, string, count=0):
   """Return the tuple (new_string, number_of_subs_made) found by replacing the leftmost non-overlapping occurrences of pattern with the replacement repl."""
   #                       
   pass

パラメータの説明:
 sub()      

サンプルコード:
pattern = re.compile(r'\s+')
text = "Process finished with exit code 0"
m = pattern.subn('-', text)
print(m)
#     ('Process-finished-with-exit-code-0', 5)

二、まとめ
前の部分では、reモジュールでよく使われている10の方法を記録しただけで、ソースコードには簡単な方法やよく使われていない方法がいくつか見られます.
  • fullmatch(string, pos=0, endpos=-1)
  • start(group=0)
  • end(group=0)
  • escape(string)

  • 上記の10の方法をマスターできれば、この4つの方法を理解するのも簡単です.reモジュールの使い方はこれだけですが、間違ったところがあれば、指摘してほしいです.私自身も勉強の段階です.ありがとうございます.
    ひとつの正規のテストの小さいツールを紹介します:正規表現のテストのツールの後で、また1篇のPython 3正規表現(3)貪欲なモードと非貪欲なモードを書きます