Aspose Words替换正则字符串

文章介绍了如何在Java中使用AsposeWords库执行文本查找和替换操作,并通过TextFindAndReplacementLogger类记录每次替换过程中的细节,包括原始匹配文本和替换后的结果。
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");
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值