package com.mistray;
import com.aspose.words.*;
import java.text.MessageFormat;
import java.util.regex.Pattern;
import static sun.plugin.javascript.navig.JSType.Document;
public class Aspose {
///
/// Maintains a log of every text replacement done by a find-and-replace operation
/// and notes the original matched text's value.
///
private static class TextFindAndReplacementLogger implements IReplacingCallback {
public int replacing(ReplacingArgs args) {
System.out.println(MessageFormat.format("\"{0}\" converted to \"{1}\" {2} characters into a {3} node.", args.getMatch().group(0), args.getReplacement(), args.getMatchOffset(), args.getMatchNode().getNodeType()));
mLog.append(MessageFormat.format("\"{0}\" converted to \"{1}\" {2} characters into a {3} node.", args.getMatch().group(0), args.getReplacement(), args.getMatchOffset(), args.getMatchNode().getNodeType()));
if(args.getMatch().group(0).contains("、")){
return ReplaceAction.SKIP;
}
args.setReplacement("${P0001:{0}}".replace("{0}",args.getMatch().group(0)));
return ReplaceAction.REPLACE;
}
public String getLog() {
return mLog.toString();
}
private final StringBuilder mLog = new StringBuilder();
}
public static void main(String[] args) throws Exception {
// 创建一个新的文档
Document doc = new Document("准备替换的文档.docx");
// We can use a "FindReplaceOptions" object to modify the find-and-replace process.
FindReplaceOptions options = new FindReplaceOptions();
// Set a callback that tracks any replacements that the "Replace" method will make.
TextFindAndReplacementLogger logger = new TextFindAndReplacementLogger();
options.setReplacingCallback(logger);
doc.getRange().replace(Pattern.compile("\\d+、?"),"",options);
// Paragraph para=doc.getFirstSection().getBody().getParagraphs().get(1);
//
// Run lastRun = para.getRuns().get(0);
// lastRun.setText(lastRun.getText()+"11");
// 保存文档
doc.save("33.docx");
}
}
Aspose Words替换正则字符串
于 2024-04-14 16:10:31 首次发布
文章介绍了如何在Java中使用AsposeWords库执行文本查找和替换操作,并通过TextFindAndReplacementLogger类记录每次替换过程中的细节,包括原始匹配文本和替换后的结果。

308

被折叠的 条评论
为什么被折叠?



