zoukankan      html  css  js  c++  java
  • Python 正则表达式

     1 #!/usr/bin/env python
     2 #-*- coding:utf-8 -*-
     3 import re
     4 
     5 #match 从开头匹配
     6 a = re.match("abc","abcdef")
     7 print(a)
     8 print(a.group())
     9 
    10 a = re.match("abc","cabcdef")
    11 print(a)
    12 
    13 c = re.match("[0-9][0-9]","78d6ef")
    14 print(c)
    15 print(c.group())
    16 
    17 c = re.match("[0-9]{0,10}","78d6ef")#匹配0到10次
    18 print(c.group())
    19 
    20 c = re.match("[0-9]{2}","7890d6ef")#匹配两次
    21 print(c.group())
    22 
    23 #findall 匹配所有
    24 d = re.findall("[0-9]{1,10}","123abcde45eg")
    25 print(d)
    26 
    27 d = re.findall("[a-zA-Z]{1,10}","123abcde45eg")
    28 print(d)
    29 
    30 #匹配任意字符
    31 e = re.findall(".*","123456abcde")
    32 print(e)
    33 
    34 #搜索
    35 f = re.search("d+","75_46.5 4a~bc6@def")
    36 print("f is {0}".format(f.group()))
    37  
    38 f = re.search("^d+$","752343445")#匹配以数字开头和以数字结尾
    39 print("f is {0}".format(f.group()))
    40 
    41 #替换
    42 g = re.sub("d+","|","adf75_46.5 4a~bc6@def",count=2)#将匹配的数字替换成|,替换两个,若没有count则全部替换
    43 print('g is {0}'.format(g))

    <_sre.SRE_Match object; span=(0, 3), match='abc'>
    abc
    None
    <_sre.SRE_Match object; span=(0, 2), match='78'>
    78
    78
    78
    ['123', '45']
    ['abcde', 'eg']
    ['123456abcde', '']
    f is 75
    f is 752343445
    g is adf|_|.5 4a~bc6@def

  • 相关阅读:
    Spring 基础学习
    Swagger basics (one)
    Handsontable Basics V7(one)
    JavaScript 对象
    CSS 基础总结
    Shell Programming(three)
    Shell Programming(two)
    Shell Programming(one)
    HTML标签总结
    jQuery 基础
  • 原文地址:https://www.cnblogs.com/Presley-lpc/p/9236317.html
Copyright © 2011-2022 走看看