Home  >  Article  >  Backend Development  >  Detailed explanation of Python regular simple example code

Detailed explanation of Python regular simple example code

高洛峰
高洛峰Original
2017-03-22 09:25:421367browse

This article mainly introduces Python simple regular examples, and specifically analyzes the problems and related precautions encountered in Python's simple regular matching test for strings , friends in need can refer to

The examples in this article describe the simple usage of Python regular expressions. I share it with you for your reference. The details are as follows:

I quietly broke into a small group of Python enthusiasts in UED within the company. Two days ago, an awesome person sent a message:

Small Test question:

re.split('(\W+)', ' test, test, test.')

What results are returned

At first, I didn’t notice that W was uppercase. I thought it was a lowercase w representing a word character (including underline). I ran it today and took a look. Discovery is capitalized.

The results of running IDLE are as follows:

>>> import re
>>> re.split('(\W+)', ' test, test, test.')
['', ' ', 'test', ', ', 'test', ', ', 'test', '.', '']
>>>

When I saw the above output, I was confused. \W matches non-word characters, so why are there so many non-words in the results? character?

I even suspected that I had remembered the meaning of \W wrongly. I opened the regular manual and checked to make sure that I remembered it correctly. I found that the matching pattern in this example included parentheses, which corresponded to the regular expression. (pattern),

This means that the match will be obtained while matching and saved to the matching result set.

Suddenly.

Test again:

>>> re.split('(\W+)', ' test, test, test.')
['', ' ', 'test', ', ', 'test', ', ', 'test', '.', '']
>>> re.split('\W+', ' test, test, test.')
['', 'test', 'test', 'test', '']
>>>

The above is the detailed content of Detailed explanation of Python regular simple example code. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn