字符串处理神器——Python Regular Expression

正则表达式是一个特殊的字符序列(也可以理解为匹配模式)

它可以帮助方便地检查文本是否与该模式匹配。

匹配的信息包括匹配的子串、分组和在本文中的索引等等。

在python中所有正则表达式的函数都在模块re中,有很多与字符串操作类似的函数。

放一些在ECNU Online Judge上能用re处理的例题(后续遇到了再更新~)

 1、EOJ 2897 英文缩写词

传送门:http://acm.ecnu.edu.cn/problem/2897/

除了预处理+stringstream的标准做法之外,使用re.split有奇效

import re
del_word = ["THE", "AN", "A", "OF", "FOR", "AND"]
while True:
    try:
        for word in re.split(r"[ -]", input().upper()):
            if not (word in del_word):
                print(word[0], end = '')
        print('')
    except:
        break

2、EOJ 3124 英文缩写词

传送门:http://acm.ecnu.edu.cn/problem/3124/

 这题的大致思路是:用标点和空格分割字符,filter过滤后用set去重,最后排序

import re
cas = int(input())
for t in range(cas):
    s = input()
    print("case #%d:" %t)
    lis = list(set(filter(lambda x: x, re.split(r'[,.!? ]+', s))))
    lis.sort()
    print(' '.join(lis))

 Tips:当输出要求各个数字/字符串用空格隔开时(有的还要求没有行末空格)

python的常规输出会很麻烦。

一个解决的办法是将存放输出结果的list转成str类型(lambda一下

 然后像上面代码一样join输出。


 3、EOJ 3143 纯虚数的幂

传送门:http://acm.ecnu.edu.cn/problem/3143/

这题用python做直接解决了高精度问题,需要做的就是利用re.split将a和b提取出。

from re import split
cas = int(input())
for t in range(cas):
    a, b = map(int, split(r"[j ]+", input()))
    s = str(a ** b)
    dic = {0: s, 1:s+'j', 2:'-'+s, 3:'-'+s+'j'}
    print("case #%d:\n%s" %(t, dic[b%4]))

 4、EOJ 2959 正则表达式简化版

传送门:http://acm.ecnu.edu.cn/problem/2959/

题意就是给定一个模式串和若干文本串,问文本串是否和模式匹配。

上来用re直接search,WA了几发以后发现了问题所在:

python自带的正则表达式系统在文本串和模式串过长的情况下会抛出OverFlowError

当数据过大搜索持续的时候会RE(出题人硬要卡Python咯?)

所以可以改成一旦catch到Error就认为匹配失败就蜜汁AC了(雾)

from re import search
while True:
	try:
		s = input()
		while True:
			try:
				text = input()
				if text == '0': break
				m = search(s, text)
				print('Regular Expression is Fun!') if m else print('Boring String Matching...')
			except OverflowError:
				print('Boring String Matching...')
	except:
		break




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值