Regular Expression
Funeral Blues
Stop all the clocks, cut off the telephone,
Prevent the dog from barking with a juicy bone,
Silence the pianos and with muffled drum
Bring out the coffin, let the mourners come.
Let aeroplanes circle moaning overhead
Scribbling on the sky the message He Is Dead.
Put crepe bows round the white necks of public doves,
Let the traffic policemen wear black cotton gloves.
He was my North, my South, my East and West.
My working week and my Sunday rest,
My noon, my midnight, my talk, my song;
I thought that love would last forever; I was wrong.
The stars are not wanted now: put out every one;
Pack up the moon and dismantle the sun;
Pour away the ocean and sweep up the wood;
For nothing now can ever come to any good.
import re
text=''
file =open('d:\poem.txt')
for line in file:
text=text+line
file.close()
result=re.findall(' to ',text)
print(result)
[' to ']
Process finished with exit code 0
import re
text=''
file =open('d:\poem.txt')
for line in file:
text=text+line
file.close()
result=re.findall('a.. ',text)
print(result)
['all ', 'and ', 'age ', 'ack ', 'ast ', 'and ', 'and ', 'ast ', 'ars ', 'are ', 'ack ', 'and ', 'and ', 'any ']
Process finished with exit code 0
a【a-z】c
import re
text=''
file =open('d:\poem.txt')
for line in file:
text=text+line
file.close()
result=re.findall('a[a-z][a-z] ',text)
print(result)
import re
text=''
file =open('d:\poem.txt')
for line in file:
text=text+line
file.close()
result=re.findall(' a[a-z][a-z]',text)
print(result)
[' all', ' and', ' aer', ' and', ' and', ' are', ' and', ' awa', ' and', ' any']
Process finished with exit code 0
import re
text=''
file =open('d:\poem.txt')
for line in file:
text=text+line
file.close()
result=re.findall(' a[a-z][a-z]',text)
result=set(result)
#去掉重复的结果
print(result)
{
' are', ' all', ' awa', ' aer', ' any', ' and'}
Process finished with exit code 0
import re
text=''
file =open('d:\poem.txt')
for line in file:
text=text+line
file.close()
result=re.findall('(a[a-z][a-z])|(A[a-z][a-z])',text)
result=set(result)
#去掉重复的结果
print(result)
#a*空的,a,aa,aaaa,aaa
{
('ack', ''), ('ano', ''), ('aff', ''), ('alk', ''), ('aer', ''), ('and', ''), ('ane', ''), ('are', ''), ('ant', ''), ('ast', ''), ('awa', ''), ('ark', ''), ('any', ''), ('ars', ''), ('ani', ''), ('all', ''), ('age', '')}
Process finished with exit code 0
`
```csharp
import re
text=''
file =open('d:\poem.txt')
for line in file:
text=text+line
file.close()
result=re.findall('(a[a-z][a-z])|(A[a-z][a-z])',text)
final_result=set()
for pair in result:
if pair[0] not in final_result:
final_result.add(pair[0])
if pair[1] not in final_result:
final_result.add(pair[1])
#去掉重复的结果
print(final_result)
#a*空的,a,aa,aaaa,aaa
{
'', 'ano', 'ars', 'and', 'ani', 'alk', 'ant', 'ast', 'ark', 'awa', 'any', 'age', 'all', 'ack', 'aer', 'aff', 'ane', 'are'}
Process finished with exit code 0
\d一个数字
hello world 123
result.re.finall(’\d+’,text)
print(result)
+至少有一个数字
\d+至少有一个数字
\d{2,3}匹配两个-三个数字
\w{3,10}