视频的容积 发表于 2018-8-12 10:44:00

python基础(5)--正则表达式

  In : import re          #加载正则表达式模块
  In : url = 'www.hello.com'
  In : pat = re.compile(r'he..')   #定义匹配的模式
  In : mat = pat.search(url)      #将定义的模式用于url搜索   ,search只搜索匹配第一次出现的,findall搜索出全部匹配的返回为列表。
  In : mat.group()         #返回搜索的内容,mat.groups()是返回的列表,当出现多次时候就会出现列表
  Out: 'hell'
  In : mat.pos               #属性,搜索字符串的起始位置(从字符串的哪个位置开始搜索的)
  Out: 0
  In : mat.endpos   #搜索字符串的结束位置(从字符串的哪个位置结束搜索的)
  Out: 15
  In : mat.start             #这个是函数
  Out: <function start>
  In : mat.start()               #匹配到的起始位置
  Out: 4
  In : mat.end()                  #匹配到的结束位置
  Out: 8
  In : re.findall('m',url)      #返回多次匹配到的结果,形成列表
  Out: ['m', 'm']
  分割 re.split()
  In : f1=open('/etc/passwd','r')
  In : re.split(':',f1.read)      #将冒号替换为分隔符
  f1.read       f1.readinto   f1.readline   f1.readlines
  In : re.split(':',f1.readli)
  f1.readline   f1.readlines
  In : re.split(':',f1.readline())
  Out: ['root', 'x', '0', '0', 'root', '/root', '/bin/bash\n']
  原文件内容: root:x:0:0:root:/root:/bin/bash
  查找替换
  In : re.sub('he','HE',url)
  Out: 'www.HEllo.com'
页: [1]
查看完整版本: python基础(5)--正则表达式