Tools, FAQ, Tutorials:
re.search() - Search for First Match
How to search for the first match of a regular expression using re.search()?
✍: FYIcenter.com
The re.search() function allows you to search for the first match
of a given regular expression in a target string.
import re m = re.search(pattern, string, flags=0) Where: pattern is the regular expression string is the target string m is None or a Match object
If a match is found, m is the Match object representing the match result, which supports the following properties and functions:
import re m = re.search(pattern, string, flags=0) m.re # the regular expression m.string # the target string m.group() # the matched substring m.group(1) # the first matched group m.group(2) # the second matched group ... m.groups() # all matched groups as tuple m.start() # the starting position of the match m.start(1) # the starting position of the first matched group m.start(2) # the starting position of the second matched group ... m.end() # the ending position of the match m.end(1) # the ending position of the first matched group m.end(2) # the ending position of the second matched group ...
Here is a Python example that shows you how to use the re.search() function and the match result object:
>>> import re
>>> s = "Hello perl.org, php.net, and python.org!"
>>> p = "(\\w+)\\.(\\w+)"
>>> print(p)
(\w+)\.(\w+)
>>> m = re.search(p,s)
>>> print(m)
<_sre.SRE_Match object; span=(6, 14), match='perl.org'>
>>> m.group()
'perl.org'
>>> m.group(1)
'perl'
>>> m.group(2)
'org'
>>> m.groups()
('perl', 'org')
>>> m.start()
6
>>> m.end()
14
⇒ re.findall() - Find All Matches
2018-10-19, ∼3947🔥, 0💬
Popular Posts:
How to use the "return-response" Policy statement to build the response from scratch for an Azure AP...
How to use the "find-and-replace" Policy Statement for an Azure API service operation? The "find-and...
How to start Visual Studio Command Prompt? I have Visual Studio 2017 Community version with Visual C...
How to use the XML to JSON Conversion Tool at freeformatter.com? If you want to try the XML to JSON ...
What is EPUB 3.0 Metadata "dcterms:modified" property? EPUB 3.0 Metadata "dcterms:modified" is a req...