Python中使用正则表达式

本文通过示例来描述如何在Python中使用正则表达式来统计文本中的所有数字。

示例中的文本来自命令行的管道数据,

sys.stdin.readlines()

主要是因为作者需要在命令行的输出信息中做数字统计。


示例代码1,列出根目录下所有文件或文件夹的名称字符串中包含的数字

import re
for name in sys.stdin.readlines():
  items = re.findall("\d+", name)
  if(len(items)>0):
    print items

执行命令:

$ ls /
bin  boot  cdrom  dev  etc  home  initrd.img  initrd.img.old  lib  lib32  lib64  libx32  lost+found  media  mnt  opt  proc  root  run  sbin  selinux  srv  sys  tmp  usr  var  vmlinuz  vmlinuz.old

$ ls / | python test.py

输出结果:

['32']
['64']
['32']

示例代码2:找出管道输出文本中的所有数字,并求和

import sys;
import re

items = []
for name in sys.stdin.readlines():
  nums = re.findall("\d+", name)
  for num in nums:
    items.append(num)

if(len(items)>0):
    print items

sumNum = 0
for num in items:
  sumNum += int(num)

print "Total:",sumNum


正则表达式的规则如下图:


Python使用正则表达式匹配文字符,你可以使用Unicode属性或者特定的Unicode范围来匹配。文字符一般位于Unicode编码的Basic Multilingual Plane (BMP)的CJK统一汉字区域,其编码范围大致是从`\u4e00`到`\u9fff`。以下是一些示例代码,展示了如何使用正则表达式来匹配文字符: ```python import re # 使用Unicode范围匹配文字符 pattern = r'[\u4e00-\u9fff]' text = "这是一个包含文字符的字符串文" matches = re.findall(pattern, text) print(matches) # 输出匹配到的文字符列表 # 使用Unicode属性 \p{L} 匹配任何语言的字母字符,包括文 pattern = r'\p{L}' text = "这是一个包含文字符的字符串文" matches = re.findall(pattern, text) print(matches) # 输出匹配到的文字符列表 # 使用re.UNICODE或re.U标志,这样\w、\W、\b、\B、\d、\D、\s和\S会匹配所有字符 pattern = r'\w' text = "这是一个包含文字符的字符串文" matches = re.findall(pattern, text, flags=re.UNICODE) print(matches) # 输出匹配到的文字符和字母数字字符列表 # 注意:在Python 3正则表达式模块默认就是支持Unicode的 ``` 在使用正则表达式匹配文字符时,你需要注意Python版本和库对Unicode的支持。在Python 3正则表达式模块默认支持Unicode,而Python 2可能需要在模式字符串加入`u`前缀来确保模式字符串被作为Unicode字符串处理。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值