Python fnmatch模块和compile正则匹配的使用

fnmatch模块

  • fnmatch
    全称是file name match,文件名匹配。支持unix shell的通配符。
模式含义
*匹配所有
匹配所有单个字符
  • fnmatch.fnmatch(filename, pattern)函数的使用
    匹配filename文件名的pattern模式。使用底层操作系统的大小写敏感模式。

  • 示例
    匹配当前目录下txt文件夹下的所有*.txt文件名。

from fnmatch import fnmatch
import os

for file in os.listdir('.\\txt'):
	if fnmatch(file, '*.txt'):
		print("the file name is: ", file)
  • fnmatch.fnmatchcase(filename, pattern)函数的使用
    测试filename是否匹配pattern,返回True或False;在实例归一化下比较,且不使用os.path.normcase()
    使用方法完全跟fnmatch()一样。

  • 扩展使用
    虽然fnmatch是用来匹配文件的,但也可以用来匹配字符串。用作字符串的正则表达式。值得注意的是,在匹配字符串的时候,行尾的回车字符\n 也需要考虑。

#!/usr/bin/python
# -*- coding: utf-8 -*-

from fnmatch import fnmatch as match
import re

#method 1
#with open("C:\\Users\\GXP\\Desktop\\txt\\txt1.txt", "r", encoding = 'UTF-8') as openFile:
with open("C:\\Users\\GXP\\Desktop\\txt\\txt.txt", "r") as openFile:
		matchName = [field for field in openFile.readlines() if match(field, "*guo*ping*")]
		#print(line.strip()) #equal print(line, end = '')
		print(matchName)

compile函数

compile 函数用于编译正则表达式,创建模式对象,供 match()、search() 、findall()等函数使用。

  • 实例
    将一个字符串通过正则表达式匹配成一个字典对象,然后通过键值对,打印输出需要的内容。
from fnmatch import fnmatch as match
import re

line ='192.168.0.1 25/Oct/2012:14:46:34 "GET /api HTTP/1.1" 200 44 "http://abc.com/search" "Mozilla/5.0"'
#reg = re.compile('^(?P<remote_ip>[^ ]*) (?P<date>[^ ]*) "(?P<request>[^"]*)" (?P<status>[^ ]*) (?P<size>[^ ]*) "(?P<referrer>[^"]*)" "(?P<user_agent>[^"]*)"')
reg = re.compile('(?P<remote_ip>.*) "(?P<request>[^"]*)" (?P<status>[^ ]*) (?P<size>[^ ]*) "(?P<referrer>[^"]*)" "(?P<user_agent>.*)"')
regMatch = reg.match(line)
linebits = regMatch.groupdict()

print(linebits)
print()  #print one empty line
for k, v in linebits.items() :
    print(k+": "+v)

findall函数

  • 使用方式
    a = re.findall(“匹配规则”, “要匹配的字符串”)

  • 实例1

import re

str = "a123b456b"
print(re.findall(r"a(.*)b", str))
  • 实例2
    先通过compile编译成模式对象,然后在通过findall匹配出需要的结果。
    re.compile(’\d’) 这个函数的作用是仅仅匹配数字。
import re
string ='a1b2c3d4e5f6'
pattern = re.compile('\d')  # 匹配数字
reg_l = pattern.findall(string)
print(reg_l)
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值