Share a simple code example of Python regularity

Y2J
Release: 2017-05-04 13:17:43
Original
1742 people have browsed it

This article mainly introduces simple examples of Python regularity, and specifically analyzes the problems and related precautions encountered in Python's simple regularity matching test for strings. Friends in need can refer to the examples of this article

Describes 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 Share a simple code example of Python regularity. 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