1.3 Regular expressions and the python language - 1.3.4 Use the match() method to match strings

1.3.4 Using the match() method to match strings

Python code is written in Jupyter Notebook, mainly python3 code, please forgive me for any incompatibilities. I am a novice. Although I have learned the basics of the python language by myself before, I still feel very vague after learning it.

The main purpose is to familiarize yourself with the code knowledge in the python core programming book and deepen your understanding. The result of the program operation is very simple, and the basic remarks in the program code are clear.

First, we need to know the basic usage and function of the match() function:

match() is the first re module function and regex object method to be introduced.

The match() function attempts to match the pattern from the beginning of the string. If the match succeeds, it returns a match object; if the match fails, it returns None , and the group() method of the match object can be used to display the successful match.

Here is an example of how to use match() (and group()

1  import re # import the re module of the regular expression 
2  # pattern "foo" exactly matches the string "foo", we are also able to confirm that m is an example of a match object in the interactive interpreter 
3 m = re.match( ' foo ' , ' foo ' ) #pattern match string 
4  if m is  not None: #if the match is successful, output the matching content 
5      print (m.group())
 6      print ( " exact match string " )
 7      print (m)
# AttributeError exception (None is the returned error value, this value does not have the group() attribute [method]) 
m = re.match( ' foo ' , ' bar ' ) # The pattern does not match the string 
if m is   not None:       # (single-line version of if statement) 
    print (m.group())
 else :
     print ( " pattern does not match string " )
# As long as the pattern matches from the beginning of the string, the match will still succeed even if the string is longer than the pattern. For example, the pattern " foo " will find a match in the string " food on the table " because it is Matches from the beginning of the string 
.
m = re.match( ' foo ' , ' food on the table ' ) #match successfully if m is not None: print ( " matched successfully " ) print (m.group())
#As you can see, even though the string is longer than the pattern, matching from the beginning of the string will succeed. 
#The string 'foo' is the matching part extracted from the relatively long string using Python's native object-oriented features, ignoring the results generated by the intermediate process #If the matching fails, an AttributeError exception will be thrown re.match( ' foo ' , ' food on the table ' ).group() # re.match('foo','sssfoo').group()#The match fails and does not match from the beginning of the string

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325891712&siteId=291194637