Created
March 14, 2017 06:30
-
-
Save tanchao90/aaa91d162e677c5137991ea166dec7e7 to your computer and use it in GitHub Desktop.
Python Regular Example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- coding:utf-8 -*- | |
import re | |
def testReChinese(): | |
"""测试匹配中文信息""" | |
source = "狗b狗B骂你祖宗" | |
temp = source.decode('utf8') | |
print "同时匹配中文英文" | |
print "--------------------------" | |
xx = u"狗[^一-龥]*[Bb痹逼]|肛[^一-龥]*门|狗屎吃多|骂你祖宗|天天骂你" | |
pattern = re.compile(xx) | |
results = pattern.findall(temp) | |
for result in results: | |
print result | |
print "--------------------------" | |
def testReplace(): | |
print re.search('[abc]', 'Mark cook').group() | |
print re.sub('[abc]', 'o', 'Mar cook') | |
print re.sub('[abc]', 'o', 'rock') | |
print re.sub('[abc]', 'o', 'caps') | |
def testReplaceText(): | |
source = "狗b狗B骂你祖宗nidaye" | |
text = source.decode('utf8') | |
xx = u"狗[^一-龥]*[Bb痹逼]|肛[^一-龥]*门|狗屎吃多|骂你祖宗|天天骂你|nida" | |
pattern = re.compile(xx) | |
def replaceFun( matched ): | |
matchStr = matched.group( 0 ) | |
return '*' * len(matchStr) | |
result = pattern.sub( replaceFun, text ) | |
print result | |
def testMatch(): | |
m = re.match(r'(\w+) (\w+)(?P<sign>.*)', 'hello world!') | |
print "m.string:", m.string | |
print "m.re:", m.re | |
print "m.pos:", m.pos | |
print "m.endpos:", m.endpos | |
print "m.lastindex:", m.lastindex | |
print "m.lastgroup:", m.lastgroup | |
print "m.group(1,2):", m.group(1, 2) | |
print "m.groups():", m.groups() | |
print "m.groupdict():", m.groupdict() | |
print "m.start(2):", m.start(2) | |
print "m.end(2):", m.end(2) | |
print "m.span(2):", m.span(2) | |
print r"m.expand(r'\2 \1\3'):", m.expand(r'\2 \1\3') | |
def testPatern(): | |
p = re.compile(r'(\w+) (\w+)(?P<sign>.*)', re.DOTALL) | |
print "p.pattern:", p.pattern | |
print "p.flags:", p.flags | |
print "p.groups:", p.groups | |
print "p.groupindex:", p.groupindex | |
if __name__ == '__main__': | |
# testReChinese() | |
testReplace() | |
# testReplaceText() | |
# testMatch() | |
# testPatern() | |
pass |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment