Get the App
SLTechnology News&Howtos  ›  Development  › 

How does Python define the regular expression to achieve the shortest match

Shulou Source: shulou.com Published: 2022-06-03 17:44:28 10月04日 Update

This article focuses on "Python how to define regular expressions to achieve the shortest matching", interested friends may wish to take a look. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn "how Python defines the regular expression to achieve the shortest match".

1. Demand

We are trying to match text patterns with regular expressions, but what is identified is the longest possible match. Instead, we want to modify it to the shortest possible match.

2. Solution

This problem usually occurs when the matching text is wrapped by a pair of beginning and ending delimiters (such as a quoted string). To illustrate this problem, take a look at the following example:

Import restr_pat=re.compile (r'\ "(. *)\") text1='mark say "love" 'text2='mark say "love", jingjing say "yes"' print (str_pat.findall (text1)) print (str_pat.findall (text2)

Results:

['love'] [' love ", jingjing say" yes']

In this example, the pattern r'"(. *)" tries to match the text contained in quotation marks. However, the * operator uses a greedy strategy in regular expressions, so the matching process is based on finding the longest possible match. That's why the match [love ", jingjing say" yes] appears above.

To solve this problem, just add after the * operator in the pattern? Modifiers are fine.

Example:

Import restr_pat=re.compile (r'\ "(. *?)\") text1='mark say "love" 'text2='mark say "love", jingjing say "yes"' print (str_pat.findall (text1)) print (str_pat.findall (text2)

Results:

['love']

['love',' yes']

This ensures that the matching process will not be greedy and will result in the shortest match.

At this point, I believe you have a deeper understanding of "Python how to define the regular expression to achieve the shortest match". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

Tags: Regular expression text pattern result problem longest content quotation mark operator procedure learning trying practical deeper example interest delimiter character string Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Shulou Technology Linux Xiaomi MySQL NVidia