【韦德国际1946手机版】正则表明式,python正则表

作者: 韦德国际1946手机版  发布:2019-09-03

【韦德国际1946手机版】正则表明式,python正则表明式。python 正则表达式,python

 

#conding:utf-8
__author__ = 'similarface'
import sys
#子字符串选择
print('HK usa china'[5:10])                         #a chi
#字符串可以+
print('similar' 'face')                             #similarface
#匹配
print('Python is %s %s'%('good','language'))        #Python is good language
#formart String
print('Gril {} {}'.format('come','back'))           #Gril come back
#定制格式
print('boy = "%-5s",% 06d' % ('age',18))            #boy = "age  ", 00018
print('gril = "{0:<5}", {1: 06}'.format('lucy', 18))#gril = "lucy ",  00018

str='0123456789'
print(str.find('2'))        #2-->index
print(str.replace('0','!'))     #!123456789
print(str.rjust(13,'*'))        #***0123456789
print(str.isdigit())#True
#sys.stdout.write(('.'*4).join(sys.stdin.read().split('t')))
print('-'.join(str.split('0')))

import re
text1 = 'Hello boy...World'
text2 = 'Hello gril...You'
print(repr(re.match('Hello(.*)World',text1)))#<_sre.SRE_Match object; span=(0, 17), match='Hello boy...World'>
print(re.match('Hello(.*)World',text1).group(1))# boy...
#提前编译
pattobj=re.compile('Hello(.*)Word')
pattobj.match(text1)
print(re.match('Hello(.*)World',text2))#None

print('----------------')
patt='[ t]*China[ ] (.*)[Aa]rab'
line="  China is willing to cooperate with okArab "
mobj=re.match(patt,line)
print(mobj.group(0))
print(mobj.group(1))

strdemo='111--222==333'
print(re.split('--',strdemo))           #['111', '222==333']
print(re.sub('--','...',strdemo))       #111...222==333
print(re.split('--|==',strdemo))        #['111', '222', '333']
print(re.sub('--|==','...',strdemo))    #111...222...333
print(re.split('[ =]','1 2=3'))         #['1', '2', '3']
#(--)|(==)表示一组匹配式
print(re.split('(--)|(==)', strdemo))            #['111', '--', None, '222', None, '==', '333']
#? 这人表示是否存在
print(re.split('(?:--)|(?:==)', 'aaa--bbb==ccc'))#['aaa', 'bbb', 'ccc']

#('spam', 'ham')
re.search('<(.*?)>/?<(.*?)>', 'todays menu: <spam>/<ham>...<eggs><s>').groups()
#[('spam', 'ham'), ('eggs', 'cheese')]
re.findall('<(.*?)>/?<(.*?)>', '<spam>/<ham> ... <eggs><cheese>')
#[]
re.findall('<(.*?)>.*<(.*?)>', '<spam> n <ham>n<eggs>')
#[('spam', 'eggs')]
re.findall('(?s)<(.*?)>.*<(.*?)>', '<spam> n <ham>n<eggs>') #贪婪模式
#[('spam', 'ham')]
re.findall('(?s)<(.*?)>.*?<(.*?)>', '<spam> n <ham>n<eggs>')#非贪婪模式
#{'part1': 'aaa', 'part2': 'bbb', 'part3': 'ccc'}
re.search('(?P<part1>w*)/(?P<part2>w*)/(?P<part3>w*)', '...aaa/bbb/ccc]').groupdict()

#['aaa', 'bbb', 'ccc', 'ddd', 'e&e*e']
line = 'aaa...bbb-ccc / ddd.-/e&e*e'
re.findall('[^ .-/] ', line)

print('-----xx------xx------')
pattern,string="A.C","xxABCDxx"
matchobj=re.search(pattern,string)
if matchobj:
    print(matchobj.start())

pattobj = re.compile("A.*C.*")
matchobj=pattobj.search(string)
if matchobj:
    print(matchobj.start())

print(re.search(" *A.C[DE][D-F][^G-ZE]Gt ?","..ABCDEFGt..").start())
print(re.search("A|XB|YC|ZD", "..AYCD..").start())
print(re.search(r"bABCD", "..ABCD ").start())
print(re.search(r"ABCDb", "..ABCD ").start())

###GROUPS###
#每个() 就是一组 从1.开始递增
patt=re.compile("A(.)B(.)C(.)")
mobj=patt.match("A0BsCd")
print(mobj.group(1),mobj.group(2),mobj.group(3))#0 s d

#加了* 表示多个
patt=re.compile("A(.*)B(.*)C(.*)")
mobj=patt.match("AOOBxCssaa")
print(mobj.group(1),mobj.group(2),mobj.group(3))#OO x ssaa

print(re.search("(A|X)(B|Y)(C|Z)D", "..AYCD..").groups())
print(re.search("(?P<a>A|X)(?P<b>B|Y)(?P<c>C|Z)D", "..AYCD..").groupdict())

patt = re.compile(r"[t ]*#s*defines*([a-z0-9_]*)s*(.*)")
mobj=patt.search(" # define spam 1   2   3")
print(mobj.groups())                            #('spam', '1   2   3')

###subst####
print(re.sub('[ABC]','*','DAKCNBEJICD')) #D*K*N*EJI*D
#表示 A_ B_ C_
print(re.sub('[ABC]_','?','Da_JNF_FBB_CSQ'))#Da_JNF_FB?CSQ
#\1表示匹配的
print(re.sub('(.) spam', 'spam\1', 'x spam, y spam'))#spamx, spamy

#同上
def mapper(matchobj):
    return 'spam'   matchobj.group(1)
print(re.sub('(.) spam', mapper, 'x spam, y spam'))

 

正则表明式,python # conding:utf-8 __author__ = ' similarface ' import sys # 子字符串选拔 print ( ' HK usa china ' [5:10]) # a chi # 字符串能够+ print ( '...

python正则表明式1,python正则表明式

行使正则表明式,需求导入re这几个模块

1 >>> import re
2 >>> pattern=r'abc'
3 >>> str='abcdefghijabc11111abc'
4 >>> re.findall( pattern, str )
5 ['abc', 'abc', 'abc']
6 >>> 

r定义正则表达式的准则,这里相称abc那几个字符串

元字符([])相配贰个限制

>>> str="abc afc awc"
>>> pattern=r"a[bfw]c"
>>> re.findall( pattern, str )
['abc', 'afc', 'awc']
>>> pattern=r"a[bf]w"
>>> re.findall( pattern, str )
[]
>>> pattern=r"a[bf]c"
>>> re.findall( pattern, str )
['abc', 'afc']
>>> 

^:以...最先,用在中括号里面表示非(取反,可能说排除)

1 >>> import re
2 >>> str="ghostwu:hi my name is ghostwu, nice to meet you!"
3 >>> pattern=r"ghostwu"
4 >>> re.findall( pattern, str )
5 ['ghostwu', 'ghostwu']
6 >>> pattern=r"^ghostwu"
7 >>> re.findall( pattern, str )
8 ['ghostwu']
9 >>> 

1 >>> str="abc"
2 >>> pattern=r"a[b]c"
3 >>> re.findall( pattern, str )
4 ['abc']
5 >>> pattern=r"a[^b]c"
6 >>> re.findall( pattern, str )
7 []
8 >>> 

$:以....结尾

>>> str="ghostwu:hi my name is ghostwu, nice to meet you! Hanmeimei: Hi,ghostwu"
>>> pattern=r"ghostwu"
>>> re.findall( pattern, str )
['ghostwu', 'ghostwu', 'ghostwu']
>>> pattern=r"ghostwu$"
>>> re.findall( pattern, str )
['ghostwu']
>>> 

$在中括号中被当做普通的字符串相配

 1 >>> pattern=r"a[bcd$]"
 2 >>> re.findall( pattern, 'ab' )
 3 ['ab']
 4 >>> re.findall( pattern, 'ac' )
 5 ['ac']
 6 >>> re.findall( pattern, 'ad' )
 7 ['ad']
 8 >>> re.findall( pattern, 'abe' )
 9 ['ab']
10 >>> re.findall( pattern, 'a$' )
11 ['a$']
12 >>> 

转义字符

 1 >>> str="^ghostwu ^ghostwu ^ghostwu"
 2 >>> pattern=r"^ghostwu"
 3 >>> re.findall( pattern, str )
 4 []
 5 >>> pattern=r"ghostwu"
 6 >>> re.findall( pattern, str )
 7 ['ghostwu', 'ghostwu', 'ghostwu']
 8 >>> pattern=r"^ghostwu"
 9 >>> re.findall( pattern, str )
10 ['^ghostwu', '^ghostwu', '^ghostwu']
11 >>> 

 

韦德国际1946手机版 1

 

使用正则表明式,要求导入re那几个模块 1 import re 2 pattern=r ' abc ' 3 str= ' abcdefghijabc11111abc ' 4 re.findall( pat...

python正则表明式2,python正则表明式

同盟电话号码:

 1 >>> import re
 2 >>> pattern=r'd{3,4}-?d{8}'
 3 >>> re.findall( pattern, '021-12345678' )
 4 ['021-12345678']
 5 >>> re.findall( pattern, '02188888888' )
 6 ['02188888888']
 7 >>> re.findall( pattern, '0218888888' )
 8 []
 9 >>> re.findall( pattern, '021-8888888' )
10 []
11 >>> 

把正则表明式,编制程序成三个对象,能够拉长相称功能

>>> patterTel=re.compile( pattern )
>>> patterTel
<_sre.SRE_Pattern object at 0x7fd19ba5ab90>
>>> patterTel.findall( '021-88888888' )
['021-88888888']
>>> 

能够因而编写翻译成对象,传参(re.I),把相称格局改成忽略大小

 1 >>> pattern=r'[a-z] '
 2 >>> re.findall( pattern, 'abc' )
 3 ['abc']
 4 >>> re.findall( pattern, 'aBc' )
 5 ['a', 'c']
 6 >>> re.compile( pattern, re.I )
 7 <_sre.SRE_Pattern object at 0x7fd19b906490>
 8 >>> cPattern = re.compile( pattern, re.I )
 9 >>> cPattern.findall( 'aBc' )
10 ['aBc']
11 >>> 

match,相配到的字符是不是在 被匹配字符串的启幕,若是是,重返二个对象.

>>> pattern=r'abc'
>>> re.match( pattern, 'ghostwu abc' )
>>> re.match( pattern, 'abc ghostwu' )
<_sre.SRE_Match object at 0x7fd19b96c780>
>>> re.match( pattern, ' abc ghostwu' )
>>> res = re.match( pattern, 'abc ghostwu' )
>>> if res:
...     print '是以abc开头的'
... else:
...     print '不是以abc开头的'
... 
是以abc开头的
>>> 

search:存在就再次来到对象

>>> pattern=r'abc'
>>> re.search( pattern, 'abc ghostwu' )
<_sre.SRE_Match object at 0x7fd19b96c850>
>>> re.search( pattern, 'ghostwu abc' )
<_sre.SRE_Match object at 0x7fd19b96c780>
>>> re.search( pattern, 'ghostwu abc def' )
<_sre.SRE_Match object at 0x7fd19b96c850>
>>> re.search( pattern, 'ghostwu def' )
>>> 

finditer重回一个迭代器,findall再次回到的是列表

>>> pattern=r'abc'
>>> iterator=re.finditer( pattern, 'abc def abc ghostwu abc' )
>>> iterator.next()
<_sre.SRE_Match object at 0x7fd19b96c780>
>>> iterator.next()
<_sre.SRE_Match object at 0x7fd19b96c850>
>>> iterator.next()
<_sre.SRE_Match object at 0x7fd19b96c780>
>>> iterator.next()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration
>>> 

group方法,可以查阅match相称到的值

>>> pattern=r'abc'
>>> res=re.match( pattern, 'abc ghostwu abc' )
>>> res
<_sre.SRE_Match object at 0x7fd19b96c850>
>>> res.group()
'abc'

同等可用来迭代器重临的指标

>>> pattern=r'abc'
>>> re.finditer( pattern, 'abc ghostwu abc abc hello' )
<callable-iterator object at 0x7fd19b982190>
>>> res = re.finditer( pattern, 'abc ghostwu abc abc hello' )
>>> res.next().group()
'abc'
>>> res.next().group()
'abc'
>>> res.next().group()
'abc'
>>> res.next().group()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration
>>> 

re.sub:替换

>>> str='hello abc'
>>> str.replace( 'abc', 'ghostwu' )
'hello ghostwu'
>>> str
'hello abc'
>>> re.sub( r'abc', 'ghostwu', str )
'hello ghostwu'
>>> 

把小写的(r,s,t)字母换来大写的翼虎

>>> str='ghostwu:hi,nice to meet you!'
>>> re.sub( r'[r-t]', 'R', str )
'ghoRRwu:hi,nice Ro meeR you!'
>>> 

>>> str=r'jfsdaft jdfasfcxvt jfdsafdast'
>>> pattern=r'j.*t?'
>>> re.sub( pattern, 'javascript', str )
'javascript'
>>> re.subn( pattern, 'javascript', str )
('javascript', 1)

subn:结果中多了贰个数字,表示一共替换了有一些次

split:切割

>>> ip='127.0.0.1'
>>> ip.split( '.' )
['127', '0', '0', '1']
>>> pattern='.'
>>> re.split( pattern, ip )
['127', '0', '0', '1']

>>> str="hello, my name is ghostwu"
>>> pattern=r'[s,]'
>>> re.split( pattern, str )
['hello', '', 'my', 'name', 'is', 'ghostwu']
>>> 

一旦分割符号的花样各异,用正则的split是相比平价的

 

匹配电话号码: 1 import re 2 pattern=r ' d{3,4}-?d{8} ' 3 re.findall( pattern, ' 021-12345678 ' ) 4 [ ' 021-12345678 ' ] 5 re....

python的正则表达式,python正则表达式

本文由韦德国际1946发布于韦德国际1946手机版,转载请注明出处:【韦德国际1946手机版】正则表明式,python正则表

关键词: bv1946备用网址

上一篇:Python的优雅本领
下一篇:没有了