I am trying to write a simple regular expression in Python that recognizes either a comma or a newline, to be used as a delimiter and split() text.
I have tried the following:
delim = r'[,\n]'
delim = r'[\n,]'
delim = r',|\n'
delim = r'[,|\n]'
delim = r'(,\n)'
None of these work. The split() works fine if I make it just one or the other, such as...
delim = r','
delim = r'\n'
But not if I try and do both.
What am I missing here?
Thank you for your input.
Whole code:
data = "abc,def\nghi"
delim = r'[,\n]'
values = data.split(delim)
print(values)
You are using str.split()
, which doesn't take a regex as an argument.
Try using re.compile
on your regex string, and then using that object for the split:
import re
data = "abc,def\nghi"
delim = re.compile(r'[,\n]')
values = delim.split(data)
print(values)
Yields:
['abc', 'def', 'ghi']
This is bult-in python re module
import re
data = "abc,def\nghi"
re.split(",|\n", data)
Out[3]: ['abc', 'def', 'ghi']
You can enter the delimiter list as such ",|\\n|;|whatever|whatever2"
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.