Match () and search () are regular matching functions in Python, what is the difference between these two functions?
The match () function only detects if the re is matched at the start of the string, and search () scans the entire string lookup match , which means that match () is returned only if the 0-bit match succeeds, if it is not successful at the start position. Match () returns none
For example:
1234567891011 |
#! /usr/bin/env python
# -*- coding=utf-8 -*-
import
re
text
=
‘pythontab‘
m
=
re.match(r
"\w+"
, text)
if
m:
print
m.group(
0
)
else
:
print
‘not match‘
|
The result is: Pythontab
and
123456789101112 |
#! /usr/bin/env python
# -*- coding=utf-8 -*-
#
import
re
text
=
‘@pythontab‘
m
=
re.match(r
"\w+"
, text)
if
m:
print
m.group(
0
)
else
:
print ‘not match‘
|
The result is: not match
Search () scans the entire string and returns the first successful match
For example:
123456789101112 |
#! /usr/bin/env python
# -*- coding=utf-8 -*-
#
import
re
text
=
‘pythontab‘
m
= re.search(r
"\w+"
, text)
if
m:
print
m.group(
0
)
else
:
print
‘not match‘
|
The result is: Pythontab
That's it:
123456789101112 |
#! /usr/bin/env python
# -*- coding=utf-8 -*-
#
import
re
text
=
‘@pythontab‘
m
=
re.search(r
"\w+"
, text)
if
m:
print
m.group(
0
)
else
:
print
‘not match‘
|
The result is: Pythontab
Python Regular expression function The difference between match () and search () is detailed