Python正则表达式

1、找出一段字符串中的IP地址信息,注意(?:\d{1,3}\.)中的“?:“,是括号的非捕获属性,如果不加"?:",findall不能匹配出来,但search可以匹配,但search只能找到第一个。(?:\d{1,3}\.){3}最后的{3}代表前面括号的内容要重复三次

In [43]: ss = 'abs192.168.1.1233fsdlfjllajsdfl203.93.118.226lsjlfj'

In [44]: re.findall(r'(?:\d{1,3}\.){3}\d{1,3}', ss)
Out[44]: ['192.168.1.123', '203.93.118.226']

2、找出一段字符串中括号中的内容,如下。

In [66]: s = 'ni(hello)hao(world)'

In [67]: re.findall(r'\((.*?)\)', s)
Out[67]: ['hello', 'world']

    注意上面那个问号“?”,代表非贪婪模式,意为优先次数少的匹配。如果去掉它,将匹配出不是我们想要的结果

In [68]: re.findall(r'\((.*)\)', s)
Out[68]: ['hello)hao(world']

3、找出一个list中满足条件的项,下面示例是找出t中以0或3开头并以数字结尾的项,返回新的list

In [108]: t = ['000001', '300000', '600000']

In [109]: [n.group() for n in [re.search(r'^[03]\d+$', i) for i in t] if n != None]
Out[109]: ['000001', '300000']

4、(?P...)分组匹配

In [123]: id = '110108201006069256'

In [124]: g = re.search(r'(?P<Province>\d{3})(?P<City>\d{3})(?P<Year>\d{4})(?P<Month>\d{2})(?P<Date>\d{2})', id)

In [125]: print(g.groupdict())
Out[125]:{'Province': '110', 'City': '108', 'Year': '2010', 'Month': '06', 'Date': '06'}

5、判断一个字符串是否为数字

In [158]: s = ['1', '1.0', '1.' , '.1', '-.1', '-1.0', '-1.', '2..', '3.t']

In [159]: ex = r'[-+]?(?:\.?\d+|\d+\.?\d*)$'

In [160]: [n != None for n in [re.match(ex, i) for i in s]]
Out[160]: [True, True, True, True, True, True, True, False, False]

如要兼容科学计数法(如5e2),只需将最后的”$“改为”(?:[Ee][-+]?\d+)?$“即可

In [161]: s = ['3e2', '.3e2', '-.3e3', '-3.0e2', '3E2', '3E', '3e.']

In [162]: ex = r'[-+]?(?:\.?\d+|\d+\.?\d*)(?:[Ee][-+]?\d+)?$'

In [163]: [n != None for n in [re.match(ex, i) for i in s]]
Out[163]: [True, True, True, True, True, False, False]

6、判断一个字符串是否是整数

In [164]: s = ['5', '-5', '-05', '.5', '5.']

In [165]: ex = r'[-+]?\d+$'

In [166]: [n != None for n in [re.match(ex, i) for i in s]]
Out[166]: [True, True, True, False, False]

7、分割字符串,例:按“;”分割字符串

 In[149]: s='654;trf5;987;i9u8;0987'

 In[150]: re.findall(r'[^;]+', s)
Out[150]: ['654', 'trf5', '987', 'i9u8', '0987']

8、分割字符串,并且只提取全为为数字的项

 In[151]: s='654;trf5;987;i9u8;0987'

 In[152]: re.findall(r'(?:^|;)(\d+)', s)  #(?:^|;)表示匹配字符串开头或以;开始的项,但不提取
Out[152]: ['654', '987', '0987']

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值