清除mediawiki标记的java正则表达式
可能重复:清除mediawiki标记的java正则表达式,java,regex,performance,mediawiki,matcher,Java,Regex,Performance,Mediawiki,Matcher,可能重复: 我必须清理一些来自Confluence的内容。内容几乎是干净的;但也有一些类似的情况: [链接|]:没有url部分的链接 *[链接|]*:粗体链接(不含url部分) *文本*:粗体文本 _*文本*\斜体粗体文本 等等。 我需要编写一个正则表达式来清除所有这些,因此,我做了如下操作: String wikiCleanMarkupRegex=“\\\\[(.*?[\\\\\\\\\\..*?\\\\\]\\\\\*(.*?)\” 但这并不能解决所有问题,我的意思是,如果我在#2中给它链
我必须清理一些来自Confluence的内容。内容几乎是干净的;但也有一些类似的情况:
String wikiCleanMarkupRegex=“\\\\[(.*?[\\\\\\\\\\..*?\\\\\]\\\\\*(.*?)\”代码>
但这并不能解决所有问题,我的意思是,如果我在#2中给它链接,我会得到:
[链接|]
这不是我想要的,我想得到“链接”。。。因此,我需要一次又一次地重新分析字符串,直到找不到其他匹配项为止
这真的很慢,因为有数以百万计的记录需要清理,那么,有没有任何方法可以让正则表达式一次完成所有操作
非常感谢 因为它看起来基本上有三种代码格式:斜体、粗体和
我会做一个3遍正则表达式替换
根据您提供的输入,优先顺序应为:
/**
* FIRST REMOVE ITALICS, THEN BOLD, THEN URL
*/
public static String cleanWikiFormat(CharSequence sequence) {
return Test.removeUrl(Test.removeBold(Test.removeItalic(sequence)));
}
下面是一个示例代码:
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Test {
private static String removeItalic(CharSequence sequence) {
Pattern patt = Pattern.compile("_\\*(.+?)\\*_");
Matcher m = patt.matcher(sequence);
StringBuffer sb = new StringBuffer(sequence.length());
while (m.find()) {
String text = m.group(1);
// ... possibly process 'text' ...
m.appendReplacement(sb, Matcher.quoteReplacement(text));
}
m.appendTail(sb);
return sb.toString();
}
private static String removeBold(CharSequence sequence) {
Pattern patt = Pattern.compile("\\*(.+?)\\*");
Matcher m = patt.matcher(sequence);
StringBuffer sb = new StringBuffer(sequence.length());
while (m.find()) {
String text = m.group(1);
// ... possibly process 'text' ...
m.appendReplacement(sb, Matcher.quoteReplacement(text));
}
m.appendTail(sb);
return sb.toString();
}
private static String removeUrl(CharSequence sequence) {
Pattern patt = Pattern.compile("\\[(.+?)\\|\\]");
Matcher m = patt.matcher(sequence);
StringBuffer sb = new StringBuffer(sequence.length());
while (m.find()) {
String text = m.group(1);
// ... possibly process 'text' ...
m.appendReplacement(sb, Matcher.quoteReplacement(text));
}
m.appendTail(sb);
return sb.toString();
}
public static String cleanWikiFormat(CharSequence sequence) {
return Test.removeUrl(Test.removeBold(Test.removeItalic(sequence)));
}
public static void main(String[] args) {
String text = "[hello|] this is just a *[test|]* to clean wiki *type* and _*formatting*_";
System.out.println("Original");
System.out.println(text);
text = Test.cleanWikiFormat(text);
System.out.println("CHANGED");
System.out.println(text);
}
}
以下将提供:
Original
[hello|] this is just a *[test|]* to clean wiki *type* and _*formatting*_
CHANGED
hello this is just a test to clean wiki type and formatting
另外,如果我有像*[link |]*.\u*:A链接(没有url部分)是粗体和斜体的,我需要对它进行3次解析,一次删除斜体,另一次删除粗体,最后一次删除括号。。。这对我来说太慢了