Java wikipedia正则表达式匹配和替换

Java wikipedia正则表达式匹配和替换,java,regex,wikipedia,Java,Regex,Wikipedia,我正在研究维基百科提供的媒体维基xml,并尝试对数据进行预处理,删除和替换文本中的一些特定表达式。其中一个预处理是替换维基百科页面的所有内部链接,如下所示: 输入- text here[[foo | bar]]text here[[some.jpg | some |这是some的图像]]text here 输出- text here foo bar text here some.jpg some这是一些文本的图像 这就是我目前所能做到的- String regex = "(\\[\\[(.+?)

我正在研究维基百科提供的媒体维基xml,并尝试对数据进行预处理,删除和替换文本中的一些特定表达式。其中一个预处理是替换维基百科页面的所有内部链接,如下所示:

输入-

text here[[foo | bar]]text here[[some.jpg | some |这是some的图像]]text here

输出-

text here foo bar text here some.jpg some这是一些文本的图像

这就是我目前所能做到的-

String regex = "(\\[\\[(.+?)\\]\\]*)"; 
string.replaceAll(regex, "$2"));
这有助于我从文本中删除
[[]]
。但是我一直在尝试用空格
替换管道


感谢您的帮助。

如果您只是想清理一组特殊的字符,只需匹配这些字符即可

string.replaceAll("[\\[\\]\\|\\s]+", " ");

这将解决重复空间问题:

String regex = " \\[{2}|\\]{2} |\\|";
String result = subject.replaceAll(regex, " ");
如果要检查移除的方括号和管道是否确实是要查找的结构的一部分(即
[[word1 | word2 |…| wordN]
),也可以使用基于
\G
的模式:

String regex = "(?:\\G(?!\\A)\\|| ?\\[\\[(?=[^\\]\\[|]+(?:\\|[^\\]\\[|]+)*+\\]\\]))([^\\]\\[|]+)(?>\\]\\])?";
String result = subject.replaceAll(regex, " $1");

图案详情:

(?: # two possible starts:
    \G (?!\A) \| # 1) a start contiguous to the previous match
  | # OR
    [ ]? \[\[ # 2) the double opening square brackets
    (?= # a lookahead to test if the format is the good one
        [^\]\[|]+ (?:\| [^\]\[|]+)*+ \]\]
    )
)
([^\]\[|]+) # capture the item in group 1
(?>\]\])? # eventual double closing square brackets

\[\\[\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\。非常感谢。首先,我想我需要单独处理特殊表格。但事实上这也很有效。我想我想了一个简单的解决方案。谢谢