Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

What is the difference between match () and search () in Python

Shulou Source: shulou.com Published: 2022-06-02 14:36:13 09月24日 Update

This article introduces what is the difference between match () and search () in Python. The content is very detailed. Interested friends can use it for reference. I hope it will be helpful to you.

The match () function only detects whether the RE matches at the beginning of the string, and search () scans the entire string for a match, that is, match () returns only if the match is successful at position 0, and match () returns none if the start position is not matched successfully.

For example:

#! / usr/bin/env python#-*-coding=utf-8-*-import retext = '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 retext ='@ 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 retext = 'pythontab'm = re.search (r "\ w +", text) if m: print m.group (0) else: print' not match'

The result is: pythontab

How about this:

#! / usr/bin/env python#-*-coding=utf-8-*-# import retext ='@ pythontab'm = re.search (r "\ w +", text) if m: print m.group (0) else: print 'not match'

The result is: pythontab

Summary:

Regular expression match () function in Python

If we do not create pattern objects, we can use the match function to match regular expressions directly. In my opinion, this way is more concise, but it is not suitable for the writing of large programs, and later maintenance may be difficult, but writing some small scripts is perfectly competent.

Regular expression search () function in Python

Search function and match function are somewhat similar, both can match patterns, but match and search functions are also different, and there is a big difference. Match function can only match the beginning of the string, while search can match anywhere in the string, but it also returns the first matching pattern found. Let's use examples to understand the difference between the two.

So much for sharing the difference between match () and search () in Python. I hope the above content can help you and learn more. If you think the article is good, you can share it for more people to see.

Tags: Function position result success character string regular expression content more pattern help yes great concise difficult in between that is to say example Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno NVidia MariaDB OPPO Reno Microsoft Huawei