Let’s say you have a string and want to split a string. Then how you can do so? In this tutorial, you will learn how to split a string using the regex module with steps.
In this section, you will know all the steps that you will follow to split a string. Just follow the step for better understanding.
The first step is to import all the necessary libraries that will be used in the implementation part. Let’s import it using the import statement.
import re
The second step is to create a string where you will use the regex module to split. Use the below line of code to create a string.
sample_string = "Hello, World! Welcome to data science learner"
Now after creating a string, you will define the pattern that will be used to tell the python interpreter from where you have to split the string. In my example, I will split the string after any non-numeric or nom-alphabetical character and space.
Use the blow line of code to define the pattern.
pattern = r"[^\w']+"
After defining the regex pattern you will use the re.split() function to split a string. Additionally, You have to just pass two parameters. One is the pattern and the other is your input string.
result = re.split(pattern, sample_string)
The re.splt() function will return a list of substrings that will split from your input string. Assign it to a variable and use the print() function to display it.
Add the below line of code.
print(result)
Below is the full code
import re
sample_string = "Hello, World! Welcome to data science learner"
pattern = r"[^\w']+"
result = re.split(pattern, sample_string)
print(result)
Output
Sometimes you want a string to be split in order to get tokens. You can use a regex pattern to split the string using any pattern. The regex module will check the string for any pattern and split the string. The above steps are the answer to your question on how to split a string using the regex module.
I hope you have liked this tutorial. If you have any queries then you can contact us for more help.