国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Regex > 正文

正則表達式筆記三則

2020-03-16 21:12:57
字體:
供稿:網(wǎng)友
筆記三則,貼在這里。
 
 
首字母大小寫無關(guān)模式 
有一段時間,我在寫正則表達式來匹配Drug關(guān)鍵字時,經(jīng)常寫出 /viagra|cialis|anti-ed/ 這樣的表達式。為了讓它更美觀,我會給關(guān)鍵詞排序;為了提升速度,我會使用 /[Vv]iagra/ 而非/viagra/i ,只讓必要的部分進行大小寫通配模式。確切地說,我是需要對每個單詞的首字母進行大小寫無關(guān)的匹配。 

我寫了這樣的一個函數(shù),專門用來批量轉(zhuǎn)換。 

復制代碼代碼如下:

#convert regex to sorted list, then provide both lower/upper case for the first letter of each word 
#luf means lower upper first 

sub luf{ 
# split the regex with the delimiter | 
my @arr=sort(split(//|/,shift)); 

# provide both the upper and lower case for the 
# first leffer of each word 
foreach (@arr){s//b([a-zA-Z])/[/l$1/u$1]/g;} 

# join the keyword to a regex again 
join('|',@arr); 


print luf "sex pill|viagra|cialis|anti-ed"; 
# the output is:[aA]nti-[eE]d|[cC]ialis|[sS]ex [pP]ill|[vV]iagra 

控制全局匹配下次開始的位置 

記得jyf曾經(jīng)問過我,如何控制匹配開始的位置。嗯,現(xiàn)在我可以回答這個問題了。Perl 提供了 pos 函數(shù),可以在 /g 全局匹配中調(diào)整下次匹配開始的位置。舉例如下: 
復制代碼代碼如下:

$_="abcdefg"; 
while(/../g) 

print $&; 

其輸出結(jié)果是每兩個字母,即ab, cd, ef 

可以使用 pos($_)來重新定位下一次匹配開始的位置,如: 

復制代碼代碼如下:

$_="abcdefg"; 
while(/../g) 

pos($_)--; #pos($_)++; 
print $&; 

輸出結(jié)果: 

復制代碼代碼如下:

pos($_)--: ab, bc, cd, de, ef, fg. 
pos($_)++: ab, de. 

可以閱讀 Perl 文檔中關(guān)于 pos的章節(jié)獲取詳細信息。 

散列與正則表達式替換 
《effective-perl-2e》第三章有這樣一個例子(見下面的代碼),將特殊符號轉(zhuǎn)義。 
復制代碼代碼如下:

my %ent = { '&' => 'amp', '<' => 'lt', '>' => 'gt' }; 
$html =~ s/([&<>])/&$ent{$1};/g; 

這個例子非常非常巧妙。它靈活地運用了散列這種數(shù)據(jù)結(jié)構(gòu),將待替換的部分作為 key ,將與其對應的替換內(nèi)容作為 value 。這樣只要有匹配就會捕獲,然后將捕獲的部分作為 key ,反查到 value 并運用到替換中,體現(xiàn)了高級語言的效率。 

不過,這樣的 Perl 代碼,能否移植到 Python 中呢? Python 同樣支持正則,支持散列(Python 中叫做 Dictionary),但是似乎不支持在替換過程中插入太多花哨的東西(替換行內(nèi)變量內(nèi)插)。 

查閱 Python 的文檔,(在 shell 下 執(zhí)行 python ,然后 import re,然后 help(re)),: 

復制代碼代碼如下:

sub(pattern, repl, string, count=0) 
Return the string obtained by replacing the leftmost 
non-overlapping occurrences of the pattern in string by the 
replacement repl. repl can be either a string or a callable; 
if a string, backslash escapes in it are processed. If it is 
a callable, it's passed the match object and must return 
a replacement string to be used. 

原來 python 和 php 一樣,是支持在替換的過程中使用 callable 回調(diào)函數(shù)的。該函數(shù)的默認參數(shù)是一個匹配對象變量。這樣一來,問題就簡單了: 

復制代碼代碼如下:

ent={'<':"lt", 
'>':"gt", 
'&':"amp", 


def rep(mo): 
return ent[mo.group(1)] 

html=re.sub(r"([&<>])",rep, html) 

python 替換函數(shù) callback 的關(guān)鍵點在于其參數(shù)是一個匹配對象變量。只要明白了這一點,查一下手冊,看看該種對象都有哪些屬性,一一拿來使用,就能寫出靈活高效的 python 正則替換代碼。

發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 双柏县| 布拖县| 武川县| 环江| 兴业县| 汕头市| 保亭| 阿克| 昌邑市| 永州市| 黎川县| 天峻县| 连云港市| 马尔康县| 楚雄市| 合水县| 云霄县| 临高县| 稷山县| 穆棱市| 茌平县| 四川省| 右玉县| 佛教| 富阳市| 昌江| 罗定市| 沁阳市| 老河口市| 古交市| 静乐县| 孟村| 衡阳市| 左权县| 洛宁县| 江陵县| 东兰县| 平顶山市| 清远市| 社旗县| 亳州市|