分享

python re模块

 方海龙的书馆 2014-12-10
  1. 正则表达式(可以称为REs,regex,regex pattens)是一个小巧的,高度专业化的编程语言,它内嵌于python开发语言中,可通过re模块使用。正则表达式的  
  2.   
  3. pattern可以被编译成一系列的字节码,然后用C编写的引擎执行。下面简单介绍下正则表达式的语法  
  4.   
  5.      正则表达式包含一个元字符(metacharacter)的列表,列表值如下:    . ^ $ * + ? { [ ] \ | ( )  
  6.   
  7.    1.元字符([ ]),它用来指定一个character class。所谓character classes就是你想要匹配的字符(character)的集合.字符(character)可以单个的列出,也可以通过"-"来分隔两个字符来表示一个范围。例如,[abc]匹配a,b或者c当中任意一个字符,[abc]也可以用字符区间来表示---[a-c].如果想要匹配单个大写字母,你可以用[A-Z]。  
  8.   
  9.      元字符(metacharacters)在character class里面不起作用,如[akm$]将匹配"a","k","m","$"中的任意一个字符。在这里元字符(metacharacter)"$"就是一个普通字符。  
  10.   
  11.      2.元字符[^]. 你可以用补集来匹配不在区间范围内的字符。其做法是把"^"作为类别的首个字符;其它地方的"^"只会简单匹配 "^"字符本身。例如,[^5] 将匹配除 "5" 之外的任意字符。同时,在[ ]外,元字符^表示匹配字符串的开始,如"^ab+"表示以ab开头的字符串。  
  12.   
  13.     举例验证,  
  14.   
  15.     >>> m=re.search("^ab+","asdfabbbb")  
  16.   >>> print m  
  17.     None  
  18.     >>> m=re.search("ab+","asdfabbbb")  
  19.     >>> print m  
  20.     <_sre.SRE_Match object at 0x011B1988>  
  21.     >>> print m.group()  
  22.     abbbb  
  23.   
  24.     上例不能用re.match,因为match匹配字符串的开始,我们无法验证元字符"^"是否代表字符串的开始位置。  
  25.   
  26.     >>> m=re.match("^ab+","asdfabbbb")  
  27.     >>> print m  
  28.     None  
  29.     >>> m=re.match("ab+","asdfabbbb")  
  30.     >>> print m  
  31.     None  
  32.   
  33. #验证在元字符[]中,"^"在不同位置所代表的意义。  
  34.  >>> re.search("[^abc]","abcd")  #"^"在首字符表示取反,即abc之外的任意字符。  
  35.  <_sre.SRE_Match object at 0x011B19F8>  
  36.  >>> m=re.search("[^abc]","abcd")  
  37.  >>> m.group()  
  38.  'd'  
  39.  >>> m=re.search("[abc^]","^")  #如果"^"在[ ]中不是首字符,那么那就是一个普通字符  
  40.  >>> m.group()  
  41.  '^'  
  42.   
  43. 不过对于元字符”^”有这么一个疑问.官方文档http://docs./library/re.html有关元字符”^”有这么一句话,Matches the start  
  44.   
  45. of the string, and in MULTILINE mode also matches immediately after each newline.  
  46.   
  47. 我理解的是”^”匹配字符串的开始,在MULTILINE模式下,也匹配换行符之后。  
  48.   
  49.  >>> m=re.search("^a\w+","abcdfa\na1b2c3")  
  50.   
  51.    >>> m.group()  
  52.   
  53.  'abcdfa'  
  54.   
  55.  >>> m=re.search("^a\w+","abcdfa\na1b2c3",re.MULTILINE),  
  56.   
  57.  >>> m.group()  #  
  58.   
  59.  'abcdfa'  
  60.   
  61. 我认为flag设定为re.MULTILINE,根据上面那段话,他也应该匹配换行符之后,所以应该有m.group应该有"a1b2c3",但是结果没有,用findall来尝试,可以找到结果。所以这里我理解之所以group里面没有,是因为search和match方法是匹配到就返回,而不是去匹配所有。  
  62.   
  63.  >>> m=re.findall("^a\w+","abcdfa\na1b2c3",re.MULTILINE)  
  64.   
  65.  >>> m  
  66.   
  67.  ['abcdfa', 'a1b2c3']  
  68.   
  69.    
  70.   
  71.    3. 元字符(\),元字符backslash。做为 Python 中的字符串字母,反斜杠后面可以加不同的字符以表示不同特殊意义。  
  72.   
  73.    它也可以用于取消所有的元字符,这样你 就可以在模式中匹配它们了。例如,如果你需要匹配字符 "[" 或 "\",你可以在它们之前用反斜杠来取消它们的特殊意义: \[ 或 \\  
  74.   
  75.    4。元字符($)匹配字符串的结尾或者字符串结尾的换行之前。(在MULTILINE模式下,"$"也匹配换行之前)  
  76.   
  77.    正则表达式"foo"既匹配"foo"又匹配"foobar",而"foo$"仅仅匹配"foo".  
  78.   
  79.             
  80.   
  81.    >>> re.findall("foo.$","foo1\nfoo2\n")#匹配字符串的结尾的换行符之前。  
  82.      ['foo2']  
  83.   
  84.    >>> re.findall("foo.$","foo1\nfoo2\n",re.MULTILINE)  
  85.      ['foo1', 'foo2']  
  86.   
  87.   >>> m=re.search("foo.$","foo1\nfoo2\n")  
  88.   >>> m  
  89.   <_sre.SRE_Match object at 0x00A27170>  
  90.   >>> m.group()  
  91.   'foo2'  
  92.   >>> m=re.search("foo.$","foo1\nfoo2\n",re.MULTILINE)  
  93.   >>> m.group()  
  94.   'foo1'  
  95.   
  96.      看来re.MULTILINE对$的影响还是蛮大的。  
  97.   
  98.      5.元字符(*),匹配0个或多个  
  99.   
  100.      6.元字符(?),匹配一个或者0个  
  101.   
  102.      7.元字符(+), 匹配一个或者多个  
  103.      8,元字符(|), 表示"或",如A|B,其中A,B为正则表达式,表示匹配A或者B  
  104.   
  105.      9.元字符({})  
  106.   
  107.      {m},用来表示前面正则表达式的m次copy,如"a{5}",表示匹配5个”a”,即"aaaaa"  
  108.   
  109.  >>> re.findall("a{5}","aaaaaaaaaa")  
  110.  ['aaaaa', 'aaaaa']  
  111.  >>> re.findall("a{5}","aaaaaaaaa")  
  112.  ['aaaaa']  
  113.   
  114.    {m.n}用来表示前面正则表达式的m到n次copy,尝试匹配尽可能多的copy。  
  115.   
  116.    >>> re.findall("a{2,4}","aaaaaaaa")  
  117.  ['aaaa', 'aaaa']  
  118.    通过上面的例子,可以看到{m,n},正则表达式优先匹配n,而不是m,因为结果不是["aa","aa","aa","aa"]  
  119.   
  120.    >>> re.findall("a{2}","aaaaaaaa")  
  121.  ['aa', 'aa', 'aa', 'aa']  
  122.   
  123.    {m,n}?  用来表示前面正则表达式的m到n次copy,尝试匹配尽可能少的copy     
  124.   
  125.  >>> re.findall("a{2,4}?","aaaaaaaa")  
  126.  ['aa', 'aa', 'aa', 'aa']  
  127.   
  128.    10。元字符(  "( )" ),用来表示一个group的开始和结束。  
  129.   
  130.    比较常用的有(REs),(?P<name>REs),这是无名称的组和有名称的group,有名称的group,可以通过matchObject.group(name)  
  131.   
  132.    获取匹配的group,而无名称的group可以通过从1开始的group序号来获取匹配的组,如matchObject.group(1)。具体应用将在下面的group()方法中举例讲解  
  133.   
  134.    
  135.   
  136.    11.元字符(.)  
  137.   
  138.  元字符“.”在默认模式下,匹配除换行符外的所有字符。在DOTALL模式下,匹配所有字符,包括换行符。  
  139.   
  140.  >>> import re  
  141.   
  142.  >>> re.match(".","\n")  
  143.   
  144.  >>> m=re.match(".","\n")  
  145.   
  146.  >>> print m  
  147.   
  148.  None  
  149.   
  150.  >>> m=re.match(".","\n",re.DOTALL)  
  151.   
  152.  >>> print m  
  153.   
  154.  <_sre.SRE_Match object at 0x00C2CE20>  
  155.   
  156.  >>> m.group()  
  157.   
  158.  '\n'  
  159.   
  160.    
  161.   
  162.  下面我们首先来看一下Match Object对象拥有的方法,下面是常用的几个方法的简单介绍  
  163.   
  164.  1.group([group1,…])  
  165.   
  166.   返回匹配到的一个或者多个子组。如果是一个参数,那么结果就是一个字符串,如果是多个参数,那么结果就是一个参数一个item的元组。group1的默认值为0(将返回所有的匹配值).如果groupN参数为0,相对应的返回值就是全部匹配的字符串,如果group1的值是[1…99]范围之内的,那么将匹配对应括号组的字符串。如果组号是负的或者比pattern中定义的组号大,那么将抛出IndexError异常。如果pattern没有匹配到,但是group匹配到了,那么group的值也为None。如果一个pattern可以匹配多个,那么组对应的是样式匹配的最后一个。另外,子组是根据括号从左向右来进行区分的。  
  167.   
  168.  >>> m=re.match("(\w+) (\w+)","abcd efgh, chaj")  
  169.   
  170.  >>> m.group()            # 匹配全部  
  171.   
  172.  'abcd efgh'  
  173.   
  174.  >>> m.group(1)     # 第一个括号的子组.  
  175.   
  176.  'abcd'  
  177.   
  178.  >>> m.group(2)  
  179.   
  180.  'efgh'  
  181.   
  182.  >>> m.group(1,2)           # 多个参数返回一个元组  
  183.   
  184.  ('abcd', 'efgh')  
  185.   
  186.  >>> m=re.match("(?P<first_name>\w+) (?P<last_name>\w+)","sam lee")  
  187.  >>> m.group("first_name")  #使用group获取含有name的子组  
  188.  'sam'  
  189.  >>> m.group("last_name")  
  190.  'lee'  
  191.   
  192.    
  193.   
  194.  下面把括号去掉  
  195.   
  196.  >>> m=re.match("\w+ \w+","abcd efgh, chaj")  
  197.   
  198.  >>> m.group()  
  199.   
  200.  'abcd efgh'  
  201.   
  202.  >>> m.group(1)  
  203.   
  204.  Traceback (most recent call last):  
  205.   
  206.    File "<pyshell#32>", line 1, in <module>  
  207.   
  208.    m.group(1)  
  209.   
  210.  IndexError: no such group  
  211.   
  212.    
  213.   
  214.  If a group matches multiple times, only the last match is accessible:  
  215.   
  216.    如果一个组匹配多个,那么仅仅返回匹配的最后一个的。  
  217.   
  218.  >>> m=re.match(r"(..)+","a1b2c3")  
  219.   
  220.  >>> m.group(1)  
  221.   
  222.  'c3'  
  223.   
  224.  >>> m.group()  
  225.   
  226.  'a1b2c3'  
  227.   
  228.  Group的默认值为0,返回正则表达式pattern匹配到的字符串  
  229.   
  230.    
  231.   
  232.  >>> s="afkak1aafal12345adadsfa"  
  233.   
  234.  >>> pattern=r"(\d)\w+(\d{2})\w"  
  235.   
  236.  >>> m=re.match(pattern,s)  
  237.   
  238.  >>> print m  
  239.   
  240.  None  
  241.   
  242.  >>> m=re.search(pattern,s)  
  243.   
  244.  >>> m  
  245.   
  246.  <_sre.SRE_Match object at 0x00C2FDA0>  
  247.   
  248.  >>> m.group()  
  249.   
  250.  '1aafal12345a'  
  251.   
  252.  >>> m.group(1)  
  253.   
  254.  '1'  
  255.   
  256.  >>> m.group(2)  
  257.   
  258.  '45'  
  259.   
  260.  >>> m.group(1,2,0)  
  261.   
  262.  ('1', '45', '1aafal12345a')  
  263.   
  264.     
  265.   
  266.  2。groups([default])  
  267.   
  268.  返回一个包含所有子组的元组。Default是用来设置没有匹配到组的默认值的。Default默认是"None”,  
  269.   
  270.  >>> m=re.match("(\d+)\.(\d+)","23.123")  
  271.   
  272.  >>> m.groups()  
  273.   
  274.  ('23', '123')  
  275.   
  276.  >>> m=re.match("(\d+)\.?(\d+)?","24") #这里的第二个\d没有匹配到,使用默认值"None"  
  277.   
  278.  >>> m.groups()  
  279.   
  280.  ('24', None)  
  281.   
  282.  >>> m.groups("0")  
  283.   
  284.  ('24', '0')  
  285.   
  286.    
  287.   
  288.  3.groupdict([default])  
  289.   
  290.  返回匹配到的所有命名子组的字典。Key是name值,value是匹配到的值。参数default是没有匹配到的子组的默认值。这里与groups()方法的参数是一样的。默认值为None  
  291.   
  292.  >>> m=re.match("(\w+) (\w+)","hello world")  
  293.   
  294.  >>> m.groupdict()  
  295.   
  296.  {}  
  297.   
  298.  >>> m=re.match("(?P<first>\w+) (?P<secode>\w+)","hello world")  
  299.   
  300.  >>> m.groupdict()  
  301.   
  302.  {'secode': 'world', 'first': 'hello'}  
  303.   
  304.  通过上例可以看出,groupdict()对没有name的子组不起作用  
  305.   
  306.    
  307.   
  308.    
  309.   
  310. 正则表达式对象  
  311.   
  312.  re.search(string[, pos[, endpos]])  
  313.   
  314.  扫描字符串string,查找与正则表达式匹配的位置。如果找到一个匹配就返回一个MatchObject对象(并不会匹配所有的)。如果没有找到那么返回None。  
  315.   
  316.  第二个参数表示从字符串的那个位置开始,默认是0  
  317.   
  318.  第三个参数endpos限定字符串最远被查找到哪里。默认值就是字符串的长度。.  
  319.   
  320.  >>> m=re.search("abcd", '1abcd2abcd')  
  321.  >>> m.group()  #找到即返回一个match object,然后根据该对象的方法,查找匹配到的结果。  
  322.  'abcd'  
  323.  >>> m.start()  
  324.  1  
  325.  >>> m.end()  
  326.  5  
  327.   
  328.  >>> re.findall("abcd","1abcd2abcd")  
  329.  ['abcd', 'abcd']  
  330.   
  331.    
  332.   
  333.  re.split(pattern, string[, maxsplit=0, flags=0])  
  334.   
  335.  用pattern来拆分string。如果pattern有含有括号,那么在pattern中所有的组也会返回。  
  336.   
  337.  >>> re.split("\W+","words,words,works",1)  
  338.   
  339.  ['words', 'words,works']  
  340.   
  341.  >>> re.split("[a-z]","0A3b9z",re.IGNORECASE)  
  342.   
  343.  ['0A3', '9', '']  
  344.   
  345.  >>> re.split("[a-z]+","0A3b9z",re.IGNORECASE)  
  346.   
  347.  ['0A3', '9', '']  
  348.   
  349.  >>> re.split("[a-zA-Z]+","0A3b9z")  
  350.   
  351.  ['0', '3', '9', '']  
  352.   
  353.  >>> re.split('[a-f]+', '0a3B9', re.IGNORECASE)#re.IGNORECASE用来忽略pattern中的大小写。  
  354.   
  355.  ['0', '3B9']  
  356.   
  357.    
  358.   
  359.  如果在split的时候捕获了组,并且匹配字符串的开始,那么返回的结果将会以一个空串开始。  
  360.   
  361.  >>> re.split('(\W+)', '...words, words...')  
  362.   
  363.  ['', '...', 'words', ', ', 'words', '...', '']  
  364.   
  365.  >>> re.split('(\W+)', 'words, words...')  
  366.   
  367.  ['words', ', ', 'words', '...', '']  
  368.   
  369.    
  370.   
  371.  re.findall(pattern, string[, flags])  
  372.   
  373.  以list的形式返回string中所有与pattern匹配的不重叠的字符串。String从左向右扫描,匹配的返回结果也是以这个顺序。  
  374.   
  375.  Return all non-overlapping matches of pattern in string, as a list of strings. The string is scanned left-to-right, and matches are returned in the order found. If one or more groups are present in the pattern, return a list of groups; this will be a list of tuples if the pattern has more than one group. Empty matches are included in the result unless they touch the beginning of another match.  
  376.   
  377.  >>> re.findall('(\W+)', 'words, words...')  
  378.   
  379.  [', ', '...']  
  380.   
  381.  >>> re.findall('(\W+)d', 'words, words...d')  
  382.   
  383.  ['...']  
  384.   
  385.  >>> re.findall('(\W+)d', '...dwords, words...d')  
  386.   
  387.  ['...', '...']  
  388.   
  389.    
  390.   
  391.  re.finditer(pattern, string[, flags])  
  392.   
  393.  与findall类似,只不过是返回list,而是返回了一个叠代器  
  394.   
  395.    
  396.   
  397.   我们来看一个sub和subn的例子  
  398.   
  399.  >>> re.sub("\d","abc1def2hijk","RE")  
  400.   
  401.  'RE'  
  402.   
  403.  >>> x=re.sub("\d","abc1def2hijk","RE")  
  404.   
  405.  >>> x  
  406.   
  407.  'RE'  
  408.   
  409.  >>> re.sub("\d","RE","abc1def2hijk",)  
  410.   
  411.  'abcREdefREhijk'  
  412.   
  413.    
  414.   
  415.  >>> re.subn("\d","RE","abc1def2hijk",)  
  416.   
  417.  ('abcREdefREhijk', 2)  
  418.   
  419.  通过例子我们可以看出sub和subn的差别:sub返回替换后的字符串,而subn返回由替换后的字符串以及替换的个数组成的元组。  
  420.   
  421.  re.sub(pattern, repl, string[, count, flags])  
  422.   
  423.    用repl替换字符串string中的pattern。如果pattern没有匹配到,那么返回的字符串没有变化]。Repl可以是一个字符串,也可以是一个function。如果是字符串,如果repl是个方法/函数。对于所有的pattern匹配到。他都回调用这个方法/函数。这个函数和方法使用单个match object作为参数,然后返回替换后的字符串。下面是官网提供的例子:  
  424.   
  425. >>> def dashrepl(matchobj):...     if matchobj.group(0) == '-': return ' '...     else: retu  

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约