簡體   English   中英

Python - 用通配符替換括號之間的字符串

[英]Python - string replace between parenthesis with wildcards

我正在嘗試從字符串中刪除一些文本。 我要刪除的可能是下面列出的任何示例。 基本上是大寫和小寫的任意組合,末尾的任意整數組合,以及末尾的任意字母組合。 之間也可能有空格。

  • (磁盤 1)
  • (磁盤 5)
  • (光盤2)
  • (磁盤 10)
  • (甲部分)
  • (鉑 B)
  • (磁盤一)
  • (CD 7)
  • (CD X)

我已經有一種方法可以開始“(類型”

multi_disk_search = [ '(disk', '(disc', '(part', '(pt', '(prt' ]
if any(mds in fileName.lower() for mds in multi_disk_search): #https://stackoverflow.com/a/3389611
  for mds in multi_disk_search:
    if mds in fileName.lower():
      print(mds)
      break

那返回(disc

我不能只用括號分開,因為其他括號中可能還有其他標簽。 標簽也沒有特定的順序。 我正在尋找的通常是最后一個; 但是很多時候不是。

我認為解決方案將需要正則表達式,但我真的很迷茫。

我試過這個,但它返回的東西對我來說沒有任何意義。

regex = re.compile(r"\s*\%s\s*" % (mds), flags=re.I) #https://stackoverflow.com/a/20782251/11214013
regex.split(fileName)
newName = regex
print(newName)

返回re.compile('\\s*\\(disc\\s*', re.IGNORECASE)

有什么方法可以解決這個問題?

也許是這樣的:

rx = re.compile(r'''
    \(
     (?: dis[ck] | p(?:a?r)?t )
     [ ]?
     (?: [a-z]+ | [0-9]+ )
     \)''', re.I | re.X)

此模式僅使用正則表達式模式的基本語法,除了最終的 X 標志、詳細模式(使用此模式時,模式中的任何空白字符都將被忽略,除非它被轉義或在字符類中)。 請隨意閱讀有關 re 模塊的 python 手冊。 添加對 CD 的支持作為練習。

>>> import re
>>> def remove_parens(s,multi_disk_search):
...     mds = '|'.join([re.escape(x) for x in multi_disk_search])
...     return re.sub(f'\((?:{mds})[0-9A-Za-z ]*\)','',s,0,re.I)
...

>>> multi_disk_search = ['disk','cd','disc','part','pt']
>>> remove_parens('this is a (disc a) string with (123xyz) parens removed',multi_disk_search)
'this is a  string with (123xyz) parens removed'

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM