Tools, FAQ, Tutorials:
Use Match Group \g<n> in Replacement
How to how to use matched string and groups in replacements with re.sub()?
✍: FYIcenter.com
When calling the re.sub() function, you can use matched string and groups
in replacements with the following escape sequences:
\g<0> # represents the matched string \g<1> # represents the first group in matched string \g<2> # represents the first group in matched string ...
Here is Python example that shows you how to use matched string and groups in replacements with the re.sub() function:
>>> import re >>> s = "Hello perl.org, php.net, and python.org!" >>> p = "(\\w+)\\.(\\w+)" >>> print(p) (\w+)\.(\w+) >>> r = "www.\\g<0>" >>> print(r) www.\g<0> >>> f = re.sub(p,r,s) >>> print(f) Hello www.perl.org, www.php.net, and www.python.org! >>> r = "\\g<2>.\\g<1>" >>> print(r) \g<2>.\g<1> >>> f = re.sub(p,r,s) >>> print(f) Hello org.perl, net.php, and org.python!
⇒ re.split() - Splits with Regular Expression
⇐ re.sub() - Substitute Matches with String
2018-10-13, 2648🔥, 0💬
Popular Posts:
Where to find tutorials on Visual Studio? I want to know How to learn Visual Studio. Here is a large...
Where can I download the EPUB 2.0 sample book "The Metamorphosis" by Franz Kafka? You can following ...
What is EPUB 3.0 Metadata "dcterms:modified" property? EPUB 3.0 Metadata "dcterms:modified" is a req...
Where can I download the EPUB 2.0 sample book "The Metamorphosis" by Franz Kafka? You can following ...
How to dump (or encode, serialize) a Python object into a JSON string using json.dumps()? The json.d...