Python regular simple example analysis

  • 2020-05-27 06:01:11
  • OfStack

This article illustrates the simple use of regular Python as an example. I will share it with you for your reference as follows:

Sneaking into a small group of Python fans in the company, one of them sent a message two days ago:

Small test questions:

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

What result is returned

1 at first, I didn't notice that W is uppercase. I thought it was lowercase w for the word character (with underscore).

The results of running 1 under IDLE are as follows:

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

When I see the output above, I am confused, \W matches non-word characters, so why are there so many non-word characters in the result?

I wonder if I have misremembered the meaning of \W. After opening the regular manual 1 and making sure that I remember correctly, I find that the matching pattern in this example contains parentheses corresponding to (pattern) inside the regular.

This means that the match will be retrieved at the same time as the match and saved to the match result set.

Soon, too.

Measured again:

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

PS: here are two more handy regular expression tools for you to use:

JavaScript regular expression online testing tool:

Online regular expression generation tool:

More about Python related content to view this site project: the Python regular expression usage summary ", "Python data structure and algorithm tutorial", "Python Socket programming skills summary", "Python function using techniques", "Python string skills summary", "Python introduction and advanced tutorial" and "Python file and directory skills summary"

I hope this article is helpful to you Python programming.

Related articles: