Python – Split String by Regular Expression
You can split a string in Python with delimiter defined by a Regular Expression.
In this tutorial, we will learn how to split a string by a regular expression delimiter using
re python package.
Example 1: Split String by Regular Expression
In this example, we will take a string with items/words separated by a combination of underscore and comma.
So, the delimiter could be
,,. The regular expression to cover these delimiters is
[_,] specifies that a character could match
import re #a string str = '63__foo,,bar,_mango_,apple' #split string into chunks chunks = re.split('[_,][_,]',str) #print chunks print(chunks)
['63', 'foo', 'bar', 'mango', 'apple']
Example 2: Split String by a Class
Regular expression classes are those which cover a group of characters. We will use one of such classes,
\d which matches any decimal digit.
In this example, we will also use
+ which matches one or more of the previous character.
'\d+' would match one or more decimal digits. In this example, we will use this regular expression to split a string into chunks which are separated by one or more decimal digits.
import re #a string str = 'foo635bar4125mango2apple21orange' #split with regular expression chunks = re.split('\d+',str) print(chunks)
['foo', 'bar', 'mango', 'apple', 'orange']
In this tutorial of Python Examples, we learned how to re package to split a string using regular expressions.