【问题标题】:re.sub() - Regex for replacing last occurance of a substring in a stringre.sub() - 用于替换字符串中最后出现的子字符串的正则表达式
【发布时间】:2016-10-25 11:53:41
【问题描述】:

我正在尝试在 Python 中使用 re.sub 替换字符串中最后一次出现的子字符串,但坚持使用正则表达式模式。有人可以帮我找到正确的模式吗?

String = "cr US TRUMP DE NIRO 20161008cr_x080b.wmv"

String = "crcrUS TRUMP DE NIRO 20161008cr.xml"

我想替换最后出现的“cr”以及扩展名之前的任何内容。

所需的输出字符串是 -

"cr US TRUMP DE NIRO 20161008.wmv"
"crcrUS TRUMP DE NIRO 20161008.xml"

我正在使用re.sub 替换它。

re.sub('pattern', '', String)

请指教。

【问题讨论】:

  • pattern 是你的模式吗?好吧,那当然行不通……
  • 请显示您正在使用的实际模式和字符串。
  • 我的模式不起作用,因为我对正则表达式了解不多,所以我没有提到它。

标签: python regex string


【解决方案1】:

使用贪婪量词和捕获组:

re.sub(r'(.*)cr[^.]*', '\\1', input)

【讨论】:

  • 这很简洁,但如果输入为acr.crt则不起作用
  • @anubhava:在某些情况下这种模式不起作用,您也可以考虑使用多个点的文件名。这显然不是防水模式,它更像是一个简单的说明,说明如何使用贪婪达到最后一次出现。一旦你有了这个想法,你就可以针对特定的用例对其进行改进。
【解决方案2】:

使用str.rfind(sub[, start[, end]])函数的替代方案:

string = "cr US TRUMP DE NIRO 20161008cr_x080b.wmv"
last_position = string.rfind('cr')
string = string[:last_position] + string[string.rfind('.'):]

print(string)  #cr US TRUMP DE NIRO 20161008.wmv

此外,rfind 在这种情况下会更快:
这是测量结果:
使用str.rfind(...)0.0054836273193359375
使用re.sub(...)       :0.4017353057861328

【讨论】:

  • 最佳选择 imo。在不需要时放入正则表达式是没有意义的。在需要时将它们放入是否好已经存在争议......
  • @spectras,是的,当然。此外,在这种情况下它的工作速度要快得多
【解决方案3】:

您可以使用这个否定的前瞻正则表达式:

repl = re.sub(r"cr((?!cr)[^.])*(?=\.[^.]+$)", "", input);

RegEx Demo

RegEx 拆分:

cr         # match cr
(?:        # non-capturing group start
   (?!     # negative lookahead start
      cr   # match cr
   )       # negative lookahead end
   [^.]    # match anything but DOT
)          # non-capturing group end
*          # match 0 or more of matching character that doesn't have cr at next postion
(?=        # positive lookahead start
   \.      # match DOT
   [^.]+   # followed by 1 or more anything but DOT
   $       # end of input
)          # postive lookahead end

【讨论】:

  • 发生了这件事,很好的回应。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-03-13
  • 1970-01-01
  • 1970-01-01
  • 2012-04-26
  • 1970-01-01
  • 2011-09-10
  • 1970-01-01
相关资源
最近更新 更多