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!