Get the App
SLTechnology News&Howtos  ›  Development  › 

How to achieve minimum matching with python regular expressions

Shulou Source: shulou.com Published: 2022-06-01 05:45:06 10月12日 Update

This article is about how python regular expressions achieve minimal matching. The editor thinks it is very practical, so share it with you as a reference and follow the editor to have a look.

Minimum matching

Format:

Quantifier?

Note: the quantifiers are {nMagol m},?, +, *

Use:

Find the shortest substring in a string that meets the regular expression rules.

Case study:

The existing string num = "10-3 * (20-10 + (- 10 + (- 10-5)) 27-max) 3-(- 100) / (10-35)", to extract the contents in parentheses.

Import renum ='10-3 * (20-10 + (- 10 +) / (10-3) + (- 5) num2 6) 'num2 = re.findall ('\ (. +?\), num) num3 = re.findall ('(. +\)', num) print (num2) print (num3) out: ['(20-10 + (- 10 + 5)','(- 100)' '(10-3-5)'] [(20-10 + (- 10-10) 5) * 27-3) 3-(- 100) / (10-3-5))']

In the above code, num2 uses the minimum match, while num3 uses the default maximum match.

Notice the regular expression of num2:

. Indicates that all characters except newline characters are matched

+ represents one or more

? Represents the minimum match, followed by the first match), which returns the result. Without this? Will match to the last) before the result is returned.

Thank you for reading! This is the end of this article on "how to achieve minimum matching with python regular expressions". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, you can share it for more people to see!

Tags: Minimum regular expression character content string more article result quantifier good practical maximum code multiple parenthesis newline character article format case Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Shulou Technology Shulou Information macOS MariaDB Docker