我想处理从Wikipedia API检索到的文章,以便仅显示纯文本。我要删除的内容看起来像:
{{Infobox scientist
| name = Albert Einstein
| image = Einstein 1921 by F Schmutzer.jpg
| caption = Albert Einstein in 1921
| birth_date = {{Birth date|df=yes|1879|3|14}}
| birth_place = [[Ulm]], [[Kingdom of Württemberg]], [[German Empire]]
| death_date = {{Death date and age|df=yes|1955|4|18|1879|3|14}}
| death_place = {{nowrap|[[Princeton, New Jersey]], United States}}
| children = [[Lieserl Einstein|"Lieserl"]] (1902–1903?)<br />[[Hans Albert Einstein|Hans Albert]] (1904–1973)<br />[[Eduard
Einstein|Eduard "Tete"]] (1910–1965)
| spouse = [[Mileva Marić]] (1903–1919)<br />{{nowrap|[[Elsa Löwenthal]] (1919–1936)}}
| residence = Germany, Italy, Switzerland, Austria, Belgium, United States
| citizenship = {{Plainlist|
* [[Kingdom of Württemberg]] (1879–1896)
* [[Statelessness|Stateless]] (1896–1901)
* Switzerland (1901–1955)
* [[Austria–Hungary]] (1911–1912)
* [[German Empire]] (1914–1918)
* [[Weimar Republic]] (1919–1933)
* United States (1940–1955)
}}
现在,我想知道如何删除
{{
和}}
之间的文本。这是我尝试做的:wikitext = wikitext.replaceAll("\\{\\{(.*?)\\}\\}", "");
但这不是真的。我猜是“括号括起来”会引起问题。关于删除Stackoverflow上括号之间的文本,有很多讨论,但是我没有找到任何可以解决此问题的方法
最佳答案
您无法使用Java正则表达式来确定嵌套括号的水平。但是,对于您的仅具有一个深度级别的特定示例,并假设末尾缺少右括号,则可以使用以下命令:
\\{\\{(?>[^{}]++|\\{\\{[^}]++}})*}}
如果级别数不确定,您可以:
1)编写一个解析器,该解析器逐字符逐字符地移动,遇到
{{
时增加堆栈,而遇到}}
时减少堆栈。当标志等于零时,括号被平衡。2)执行replaceall,直到不再有与以下内容有关的替换:
\\{\\{[^{}]*}}
(与最里面的级别匹配)3)使用支持递归的第三方正则表达式库
4)找到一种处理这种格式的工具(也许已经存在)