交易员日志

 找回密码
 受邀注册
查看: 9158|回复: 0

利用正则表达式提取数字

[复制链接]

256

主题

887

帖子

898

积分

管理员

Rank: 9Rank: 9Rank: 9

积分
898
发表于 2018-9-28 21:59:55 | 显示全部楼层 |阅读模式
https://blog.csdn.net/yxstory/article/details/78265399

从字符串“127米”中提取数字127:方法一、利用正则表达式
参考:https://zhidao.baidu.com/question/328905513600600605.html
用法:

## 总结
## ^ 匹配字符串的开始。
## $ 匹配字符串的结尾。
## \b 匹配一个单词的边界。
## \d 匹配任意数字。
## \D 匹配任意非数字字符。
## x? 匹配一个可选的 x 字符 (换言之,它匹配 1 次或者 0 次 x 字符)。
## x* 匹配0次或者多次 x 字符。
## x+ 匹配1次或者多次 x 字符。
## x{n,m} 匹配 x 字符,至少 n 次,至多 m 次。
## (a|b|c) 要么匹配 a,要么匹配 b,要么匹配 c。
## (x) 一般情况下表示一个记忆组 (remembered group)。你可以利用 re.search 函数返回对象的 groups() 函数获取它的值。
## 正则表达式中的点号通常意味着 “匹配任意单字符”




  • import re


  • string = u'127米'


  • print re.findall(r"\d+\.?\d*", string)




方法二、利用filter(str.isdigit, iterable)
参考:http://blog.csdn.net/real_tino/article/details/61915570




  • string = u'127米'


  • print (filter(str.isdigit, string))



bug:TypeError: descriptor 'isdigit' requires a 'str' object but received a 'unicode'
原因:string不是str类型
修改为:




  • string = u'127米'


  • string2 = string.encode('gbk')


  • print (type(str))


  • print (filter(str.isdigit, string2))



结果:
<type 'str'>
127


注意:要提取的字符串不能命名为str,否则会出现TypeError: isdigit() takes no arguments (1 given)
因为str和filter里的str重名了。
---------------------本文来自 晓晓星辰 的CSDN 博客 ,全文地址请点击:https://blog.csdn.net/yxstory/ar ... 399?utm_source=copy
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 受邀注册

本版积分规则

Archiver|手机版|小黑屋|交易员日志

GMT+8, 2025-5-4 02:42 , Processed in 0.036320 second(s), 19 queries .

Powered by Discuz! X3.4

Copyright © 2001-2020, Tencent Cloud.

快速回复 返回顶部 返回列表