python regexp

版权声明:版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/watson243671/article/details/38458329

Simplest case -


import re
regexp = re.compile('hello')
count = 0
file = open('j.txt','r')
for line in file.readlines() :
	if regexp.search(line) :
		count = count + 1
file.close()
print(count)


Now, if you want to use wildcard pattern.


import re
regexp = re.compile('(h|H)ello')
count = 0
file = open('j.txt','r')
for line in file.readlines() :
	if regexp.search(line) :
		count = count + 1
file.close()
print(count)

If you want to search '\ten', you need use raw strings in pattern.  

regexp = re.complie('\\ten')

In this way, you have escape '\' . Other char - \t (tab) \n (a new line) ...

>>> r"Hello" == "Hello" True

>>> r"\the"  == "\\the" True

>>> r"\the" == "\the" False



猜你喜欢

转载自blog.csdn.net/watson243671/article/details/38458329