Match () and search () are regular match functions in Python, so what's the difference between these two functions?
The match () function only detects whether the re is matched at the beginning of a string, and search () scans the entire string for matching, which means match () only returns if the 0-bit match succeeds, match () Returns none
For example:
#! /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: Pythontab
and
#! /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: not match
Search () scans the entire string and returns the first successful match
For example:
#! /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: Pythontab
What about this:
#! /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: Pythontab
Summarize:
Python regular expression match () function
If you do not create pattern objects, we can use the match function to directly match the regular expression, which in my view is simpler, but not suitable for the writing of large programs, and later maintenance may be difficult, but writing a few small scripts can be perfectly competent.
Python Regular expression search () function
The search function is a bit like the match function and can match the pattern, but the match and search functions are also different, and the match function can only begin to match the beginning of the string, and search can match any position of the string. But it is also the pattern that returns the first match found. Let's look at the difference between the two by example.