Differences between python Regular Expression Functions match of and search of
- 2021-12-05 06:27:51
- OfStack
The match () function only detects whether RE matches at the beginning of string, and search () scans the whole string to find a match, that is to say, match () returns only if it matches successfully at the 0 position, and match () returns none if it does not match successfully at the beginning position
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 is: 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 is: 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 is: 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 is: pythontab
For more information on python regular functions, please see the following related articles