【问题标题】:Regex to remove statment from string [duplicate]正则表达式从字符串中删除语句[重复]
【发布时间】:2018-05-23 20:02:38
【问题描述】:

我对正则表达式很陌生,在尝试从文本字符串中删除 2 个字符串时遇到了一些问题。

我正在使用 python3 并尝试了以下方法。

'\W*(Command|exited|with|status|0)\W*

匹配字符串:Command exited with status 0

我也在寻找匹配以下内容的正则表达式。

=== stdout ===

我试过了:

'\W*(===|stdout|===)\W*

对此的任何帮助将不胜感激。 谢谢!

【问题讨论】:

  • Command|exited|with|status|0: | 是“或”不是单词分隔符。
  • 这里甚至不需要正则表达式。只需使用your_string = your_string.replace("=== stdout ===",""),其他示例也一样
  • 单引号是错字吗?否则它匹配该字符串中的单词。
  • 从模式的第一个元素开始创建/调试您的正则表达式,并且只有一次与您期望的匹配,然后添加模式的下一个元素。

标签: python regex string python-3.x


【解决方案1】:

使用 'string = re.sub('=== stdout ===', '', string)' 将您想要的文本替换为空('')。下面是一些示例代码:

import re

string = 'i think New Roman"=== stdout ===>but I don\'t he=Command exited with status 0"Arial">fun stuff'

string = re.sub('Command exited with status 0', '', string)
string = re.sub('=== stdout ===', '', string)

print(string)

记得使用'\|'在您的字符串中,而不仅仅是 '|'

【讨论】:

  • 投反对票,因为您替换了“with”或“command”的任何实例,而不是请求的字符串“Command exited with status”
  • 我稍微更改了代码以更好地匹配请求的字符串。我没有意识到正在使用'|'代替 ' '(空格)。
  • 谢谢大家,让我试试这一秒。
  • 好的,所以确实有效,但是我确实忘记了一个,特别是(没有stderr),当我尝试 re.sub('(nostder)', '', string) 时它可以工作,但是,它离开 () 并删除 nostder。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-05-31
  • 2023-03-25
  • 2018-01-26
  • 1970-01-01
  • 1970-01-01
  • 2021-01-17
  • 2014-06-20
相关资源
最近更新 更多