Python Regex 匹配和排除某些内容

标签 python regex

我试图从字符串中排除一些内容。这是一个例子:

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/

相关文章:

python - "TypeError: ' DataFrame ' object is not callable "用于 Excel 数据

python - Python 中的可重入子进程?

java - 正则表达式 - 匹配两个单词或一个单词,但优先考虑两个单词

c++ - 从字面上理解 RegEx 中的每个字符

c# - 从使用某些指定字符括起来的字符串中获取子字符串

python - 使用 cherrypy (python 2) 禁用弱密码

python - 使用 pytest 时如何组织多个测试函数的步骤?

python - Python 的 urllib 中网页的 Unicode 问题

ruby-on-rails - 在 Ruby 中解析日期

ios - 删除 Swift 中两个特定分隔符之间的字符,处理嵌套结果