1. 程式人生 > >字串處理神器——Python Regular Expression

字串處理神器——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