我试图从字符串中排除一些内容。这是一个例子:
Sony Xperia Z2 m/Smartwatch 2
和:
Sony Xperia Z2 + headphones
我只想得到
Sony Xperia Z2
在这两种情况下。
我已经能够将要删除的字符串与此匹配,但如何选择相反的字符串? 到目前为止我得到了什么:
m/([a-zA-Z 0-9]*)
编辑:我添加了另一个案例。
最佳答案
使用正则表达式拆分
re.split(r" m/| \+ ", yourString)[0]
这将适用于您的两个示例:
string1 = "Sony Xperia Z2 m/Smartwatch 2"
print re.split(" m/| \+ ", string1)[0]
# output: Sony Xperia Z2
string2 = "Sony Xperia Z2 + headphones"
print re.split(" m/| \+ ", string2)[0]
# output: Sony Xperia Z2
如果你有更多的分隔符,你可以将它们添加到 split
的模式中功能。
您还可以使用 re.split(...)[1]
来检索字符串的第二部分:
string1 = "Sony Xperia Z2 m/Smartwatch 2"
print re.split(" m/| \+ ", string1)[1]
# output: Smartwatch 2
关于Python Regex 匹配和排除某些内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27797090/