So far, we've simply searched for a static string. Regular expressions are often used in different ways to modify strings by using the ' Regexobject ' method below.
The method/property action split () slices the string in the place where the re matches and generates a list, sub () finds all the substrings that the re matches and replaces it with a different string subn () is the same as the sub (), but returns the new string and the number of replacements
Fragment A String
The ' Regexobject ' Split () method fragments the string in the place where the RE matches, and returns the list. It is similar to the split () method of strings but provides more delimiters, and split () supports only whitespace and fixed strings. As you might expect, there is also a module-level re.split () function.
Split (string [, Maxsplit = 0])
Fragments a string through a regular expression. If the capture brackets are used in the RE, their contents are returned as part of the result list. If the maxsplit is Non-zero, then only maxsplit fragments can be separated.
You can limit the number of slices by setting the Maxsplit value. When Maxsplit is not zero, only maxsplit fragments are allowed, and the remainder of the string is returned as the last part of the list. In the following example, the delimiter can be an arbitrary sequence of non-numeric alphabetic characters.
#!python
>>> p = re.compile (R ' W ')
>>> p.split (' A test, short and sweet, of Split (). ')
[' This ', ' are ', ' a ', ' test ', ' short ', ' and ', ' Sweet ', ' of ', ' split ', ' ']
>>> p.split (' A test, short and sweet, of Split (). ', 3)
[' This ', ' are ', ' a ', ' test ', short and sweet, of Split ().]
Sometimes you are not only interested in the text between delimiters, but you also need to know what the delimiter is. If the capture brackets are used in the RE, their values are also returned as part of the list. Compare the following calls:
#!python
>>> p = re.compile (R ' W ')
>>> P2 = re.compile (R ' (w) ')
>>> p.split (' This ... is a test. ')
[' This ', ' is ', ' a ', ' test ', ']
>>> p2.split (' This ... is a test. ')
[' This ', ' ...] ', ' is ', ', ' a ', ', ' ' Test ', '. ', '
Module-level Functions Re.split () the re as the first parameter, the other.
#!python
>>> re.split (' [\w]+ ', ' Words, Words, Words. ')
[' Words ', ' Words ', ' Words ', ']
>>> re.split ([\w]+) ', ' Words, Words, Words. ')
[' Words ', ', ', ' Words ', ', ', ' Words ', '. ', ']
>>> re.split (' [\w]+ ', ' Words, Words, Words. ', 1)
[' Words ', ' Words, Words. ']