【问题标题】:Remove the particular pattern from text using regex in python3在 python3 中使用正则表达式从文本中删除特定模式
【发布时间】:2019-02-10 15:51:20
【问题描述】:

我想使用正则表达式从 text.txt 中删除“2019/01/31-11:56:23.288258 1886 7F0ED4CDC704”。

text.txt
2019/01/31-11:56:23.288258 1886     7F0ED4CDC704     asfasnfs: remove datepart
2019/01/31-11:56:23.288258 1886     7F0ED4CDC704     asfasnfs: remove datepart
2019/01/31-11:56:23.288258 1886     7F0ED4CDC704     asfasnfs: remove datepart
2019/01/31-11:56:23.288258 1886     7F0ED4CDC704     asfasnfs: remove datepart

预期结果:

 asfasnfs: remove datepart
 asfasnfs: remove datepart
 asfasnfs: remove datepart
 asfasnfs: remove datepart

* 我的解决方案* 删除日期部分。我在正则表达式下面写了:

**2019/01/31-11:56:23.288258**
p = '\d{4}/\d{2}/\d{2}-d{2}:\d{2}:\d{2}.\d{6}'

import re
test = re.sub(p,'', text)

模式 p 不起作用。它按原样给出文本。而且我不确定如何使用正则表达式删除文本中的整个部分。

【问题讨论】:

  • 看起来您在模式开头的第一个 d 前面缺少反斜杠 \,因此它将匹配文字“d”而不是数字。
  • 我试过了,还是不行。
  • 好的,那么您应该将代码更新为问题中的正确正则表达式(添加反斜杠),以便其他人知道这不是问题。
  • 是的,我刚刚做了...
  • 我看到一个 forward 斜线,而不是反斜线。

标签: regex python-3.x


【解决方案1】:

试试这个

import re
p = '\d{4}\/\d{2}\/\d{2}-\d{2}:\d{2}:\d{2}.\d{6}'
test = re.sub(p,'', text)

【讨论】:

    【解决方案2】:

    尝试搜索这个:

    ^.{53}
    

    并替换为空白。

    【讨论】:

      【解决方案3】:

      你的模式只匹配字符串的第一部分。要使该模式起作用,您必须转义点以匹配它,并在 d 之前添加一个反斜杠:

      \d{4}/\d{2}/\d{2}-\d{2}:\d{2}:\d{2}\.\d{6}
                        ^                ^
      

      要匹配该部分以使其保留您的预期结果,您可以在它之后使用此模式,[ \t]+ 将匹配 1 次以上的空格或制表符。如果没有标签,则只能使用空格。

      [ \t]+\d{4}[ \t]+[A-Z0-9]{12}[ \t]+
      

      完整的模式可能如下所示:

      \d{4}/\d{2}/\d{2}-\d{2}:\d{2}:\d{2}\.\d{6}[ \t]+\d{4}[ \t]+[A-Z0-9]{12}[ \t]+
      

      regex101 上的演示 | Python demo

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多