如何从wiki字符串中删除所有文件

How to remove all files from wiki string?

本文关键字:删除 文件 字符串 wiki      更新时间:2023-09-26

我想从wiki字符串中删除所有文件,如下所示:

[[File:Edvac.jpg|thumb|[[EDVAC]], one of the first stored-program computers]]

但是"文件"可以包含wiki链接,我如何删除所有可能包含wiki链接的文件?我已经使用了这个正则表达式/'['[File:[^']]+']']/,但这不适用于包含wiki链接的文件,请注意,我不想删除其他地方的wiki链接。

如果Wiki链接中没有嵌套链接,可以使用

'['[File:[^[']]*(?:'['[[^[']]*]][^[']]*)*]]

参见regex演示

var re = /'['[File:[^[']]*(?:'['[[^[']]*]][^[']]*)*]]/g; 
var str = 'Some [[File:Edvac.jpg|thumb|[[EDVAC]], one of the first stored-program computers]] text [[File:Edvac.jpg|thumb|text here]]';
var result = str.replace(re, "");
document.body.innerHTML = result;

解释

  • '['[File:-一个文字序列[[File:
  • [^[']]*-除[]之外的零个或多个字符
  • (?:'['[[^[']]*]][^[']]*)*-零个或多个序列:
    • '['[[^[']]*]]-类型为[[text without [ and ] inside]]的字符串
    • [^[']]*-除[]之外的零个或多个字符
  • ]]-一个文字序列]]

另一个简短的变体是:'['[File:[^[']']]*('['[.*]])?[^[']']]*]]。但最好包括检查文件:图像:像:媒体:媒体:,因为它们也用于Commons的媒体嵌入的许多文章中:

str.replace(/'['[(file|image|media):[^[']']]*('['[.*]])?[^[']']]*]]/gi, '')

文件标题可以(在维基百科上,有时也可以)包含嵌套的方括号,包括其他文件。您可以使用类似的递归正则表达式来匹配平衡括号

|
  '['[File:                         # literal [[File:
    (?P<balanced>                   # subpattern for []-balanced content
      (?>[^'[']]*)                  # zero or more non-bracket chars 
                                    # (with once-only subpattern for efficiency)
      (?:                           # then a (possibly empty) sequence of...
        '[(?&balanced)']            # []-balanced content in brackets
        (?>[^'[']]*)                # followed by zero or more non-bracket chars
      )*
    )
  ']']                              # literal ]]
|x                                  # extended mode flag (ignores whitespace)

(regex101),尽管您可能不想这样做。(此外,文件标题可能包含不平衡的括号。)

如果你对Python很熟悉,你应该尝试使用mwparserfromhell,它有一个强大的解析器,可以为你识别文件引用。类似的东西

import mwparserfromhell
def has_file_prefix(link):
    return str(link.title).strip().startswith('File:')
text = 'I am a wiki page. I contain some images like [[File:Edvac.jpg|thumb|[[EDVAC]], one of the first stored-program computers [[File:Edvac2.jpg| [[nesting|nested]] file with random <nowiki>[[</nowiki> in caption ]] ]] [[ not a file ]] and lots of text.'
wikicode = mwparserfromhell.parse(text)
for file in wikicode.ifilter_wikilinks(matches=has_file_prefix):
    try:
       wikicode.remove(file)
    except ValueError:
       pass # probably tried to remove a nested file when the parent was already removed
print wikicode