Python extracts the specified content instance based on the regular expression _python

Source: Internet
Author: User
Tags in python

Python extracts the specified content based on the regular expression

Regular expressions are extremely powerful, and it is convenient to use regular expressions to extract the desired content.

The following demonstrates the use of regular expressions in Python to extract content that meets the requirements.

Instance code:

Import re 
# Regular expressions are extremely powerful, and it is convenient to use regular expressions to extract the desired content. 
# The following shows the use of regular expressions in Python to extract content that meets the requirements. There are a couple of places to pay attention to 
: # 
[1] to use () to include () the required content 
# [2] The group numbered 0 is the whole of the regular expression, and the number 1 is the first (and corresponding 
#   ) content 
# @param regex:regular expression, use () ' to group 
' result #   regular expression, with () content to be extracted 
# @param content:
  # @param index:start from 1, depends on the \p regex ' s () 
#   starting from 1, you can pass the number (where 0 is all match 
# @return: the first Match of the \p Regex 
#   only returns the first matching content 
def extractdata (regex, Content, index=1): 
  r = ' 0 ' 
  p = re.com Pile (regex) 
  m = p.search (content) 
  if m: 
    r = M.group (index) return 
  r 
 
regex = R ' (. *) field snow ' 
Content = ' first snow of the year 2002 ' 
index = 1 
print extractdata (regex, content, index) 

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.