Detailed explanation of Python regular simple example code

高洛峰
Release: 2017-03-22 09:25:42
Original
1379 people have browsed it

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.')
Copy after login

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', '.', '']
>>>
Copy after login

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', '']
>>>
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!