Import re
Datepat = Re.compile (R ' (\d+)/(\d+)/(\d+) ')
m = Datepat.match (' 11/27/2012 ')
Print (m)
Print (M.group (0))
Print (M.group (1))
Print (M.group (2))
Print (M.group (3))
Print (M.groups ())
Month, day, year = M.groups ()
Text = ' Today is 11/27/2012. Pycon starts 3/13/2013. '
Datepat.findall (text)
For month, day, year in Datepat.findall (text):
Print (' {}-{}-{} '. Format (year, month, day))
Output:
<_sre. Sre_match object; span= (0, ten), match= ' 11/27/2012 ' >
11/27/2012
11
27
2012
(' 11 ', ' 27 ', ' 2012 ')
2012-11-27
2013-3-13
Text = ' @[email protected] $python '
m = Re.search (r "\w+", text)
If M:
Print (M.group (0)) #python
Else
Print (' not match ')
Def test_findall_search ():
str1 = ' 456ABC789ABC8910ABC '
Re_str = Re.compile (R ' \d+ ')
Re_findall = Re_str.findall (str1)
Print (Re_findall) #[' 456 ', ' 789 ', ' 8910 ']
Re_search = Re_str.search (str1)
Print (Re_search) #<_sre. Sre_match object; Span= (0, 3), match= ' 456 ' >
Print (Re_search.group (0)) #456
Test_findall_search ()
This article is from the "Big Barren Sutra" blog, please be sure to keep this source http://2892931976.blog.51cto.com/5396534/1755210
Regular expression matching and finding