You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
# compare 'aa', 'bb'>>>re.search(r'([a-z])\1$','aa') !=NoneTrue>>>re.search(r'([a-z])\1$','bb') !=NoneTrue>>>re.search(r'([a-z])\1$','ab') !=NoneFalse# compare open tag and close tag>>>pattern=r'<([^>]+)>[\s\S]*?</\1>'>>>re.search(pattern, '<bold> test </bold>') !=NoneTrue>>>re.search(pattern, '<h1> test </h1>') !=NoneTrue>>>re.search(pattern, '<bold> test </h1>') !=NoneFalse
Named Grouping (?P<name>)
# group reference ``(?P<name>...)``>>>pattern='(?P<year>\d{4})-(?P<month>\d{2})-(?P<day>\d{2})'>>>m=re.search(pattern, '2016-01-01')
>>>m.group('year')
'2016'>>>m.group('month')
'01'>>>m.group('day')
'01'# back reference ``(?P=name)``>>>re.search('^(?P<char>[a-z])(?P=char)','aa')
<_sre.SRE_Matchobjectat0x10ae0f288>
Substitute String
# basic substitute>>>res="1a2b3c">>>re.sub(r'[a-z]',' ', res)
'1 2 3 '# substitute with group reference>>>date=r'2016-01-01'>>>re.sub(r'(\d{4})-(\d{2})-(\d{2})',r'\2/\3/\1/',date)
'01/01/2016/'# camelcase to underscore>>>defconvert(s):
... res=re.sub(r'(.)([A-Z][a-z]+)',r'\1_\2', s)
... returnre.sub(r'([a-z])([A-Z])',r'\1_\2', res).lower()
...
>>>convert('CamelCase')
'camel_case'>>>convert('CamelCamelCase')
'camel_camel_case'>>>convert('SimpleHTTPServer')
'simple_http_server'
>>>exp=re.compile(r'''^(https?:\/\/)? # match http or https... ([\da-z\.-]+) # match domain... \.([a-z\.]{2,6}) # match domain... ([\/\w \.-]*)\/?$ # match api or file... ''', re.X)
>>>>>>exp.match('www.google.com')
<_sre.SRE_Matchobjectat0x10f01ddf8>>>>exp.match('http://www.example')
<_sre.SRE_Matchobjectat0x10f01dd50>>>>exp.match('http://www.example/file.html')
<_sre.SRE_Matchobjectat0x10f01ddf8>>>>exp.match('http://www.example/file!.html')