[英]Python regular expression simple OR condition doesn't work?
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. 我试图用Python编写一个简单的正则表达式,该表达式可以识别逗号或换行符,以用作分隔符和split()文本。
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...
如果我只使用split(),则split()可以很好地工作,例如...
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. 您正在使用
str.split()
,它不使用正则表达式作为参数。
Try using re.compile
on your regex string, and then using that object for the split: 尝试在正则表达式字符串上使用
re.compile
,然后使用该对象进行拆分:
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 这是内置的python re模块
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" 您可以输入定界符列表,例如“,| \\ n |; | whatever | whatever2”
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.