python extracts the specified content instance from the regular expression

  • 2020-05-17 05:47:18
  • OfStack

python extracts the specified content based on the regular expression

Regular expressions are extremely powerful, and it is convenient to use them to extract what you want.

In python, you can use regular expressions to extract the required content.

Example code:


import re 
#  Regular expressions are extremely powerful, and it is convenient to use them to extract what you want.  
#  The following is a demonstration of the python In this section, we use regular expressions to extract content that meets the requirements. There are a few caveats  
#  Where:  
# [1]  Want to use () Include what you need  
# [2]  Numbers for 0 the group Is the entire content conforming to the regular expression, and is numbered as 1 Is the first 1 a ( And the corresponding  
#    the ) Content contained  
# @param regex: regular expression, use () to group the result 
#    Regular expressions are used () The content to be extracted is included  
# @param content:  
# @param index: start from 1, depends on the \p regex's () 
#    from 1 You can start by counting ( To get, where 0 It's all matched  
# @return: the first match of the \p regex 
#    Returns only the first 1 Submatched content  
def extractData(regex, content, index=1): 
  r = '0' 
  p = re.compile(regex) 
  m = p.search(content) 
  if m: 
    r = m.group(index) 
  return r 
 
regex = r' The first (.*) snow ' 
content = '2002 In the first 1 snow ' 
index = 1 
print extractData(regex, content, index) 

Thank you for reading, I hope to help you, thank you for your support of this site!


Related articles: