In string processing, regular expression is a great weapon, but it is difficult for beginners.
And how to match xx beginning with xx end of the word.
Suppose you need a matching string: Site Sea Sue Sweet The case SSE Ssee loses
A word that needs to be matched with an e ending with S.
The correct regular formula is: \bs\s*?e\b
No matter what language the regular format is the same, the following example of Python for a code demo:
Explain: In Python, the Re.findall function represents all possible options in a matching string, and the first R in FindAll () represents a row, ignoring all the escapes in the regular formula.
Text = ' Site Sea Sue Sweet The case SSE Ssee loses '
Re.findall (R ' \bs\s*?e\b ', text)
The results are: [' site ', ' Sue ', ' ssee ', ' SSE ', ' ']
Here is an explanation: the \b represents the beginning or end of a word, often delimited by punctuation, spaces, line breaks, etc.
If the \b is not preceded or preceded, the regular expression is: s\s*?e
The running result becomes
[' site ', ' se ', ' Sue ', ' swe ', ' se ', ' se ', ' SSE ', ' SSE ', ' SE ']
This match is not to guarantee the integrity of the word, as long as a word contains s*e will output.
\s represents any non-empty character, the regular expression that is easily thought of in this question is \bs.*?e\b, which is about to be \s written. But this leads to another situation where the output is:
[' Site ', ' Sea Sue ', ' Sweet ', ' SSE ', ' Ssee ']
We can see that there are sea sue and so on that is not what we expect.
And as for * nature is to match any number of characters.
and using \s*? Why, why should we add it? it. This involves the lazy pattern of regular expressions.
If you use. * means greedy mode, and. *? That means lazy mode.
Greedy mode matches the longest string as much as possible, while lazy mode matches the shortest string as much as possible.
Give me a chestnut:
For string abcgabc
Greedy mode –a.*c– Get the answer is: ABCGABC
Lazy Mode –a.*?c– The answer is: ABC,ABC
Examples refer to the programming classrooms of a website--crossing learning python