We're sorry Aspose doesn't work properply without JavaScript enabled.

Free Support Forum - aspose.com

Find & Replace Line Feed Characters in Word Document using Java

Hi, I want to implement word to replace characters (/ n). How do I? The problem I have now is the inability to locate the character index in the content (i. e. the inability to locate behind the characters of / n)

code.jpg (62.2 KB)
template.png (29.4 KB)
result.jpg (22.6 KB)

The problem is resolved!
I can insert the callback in segments before writing,
The code is as follows:

private static void replaceNodeValue(Node node, String nodeKey, String repVal, FindReplaceOptions findReplaceOptions) throws Exception {
        if (Objects.isNull(findReplaceOptions)) {
            findReplaceOptions = new FindReplaceOptions();
        String val = repVal.replaceAll(ControlChar.CR, LINE_KEY).replaceAll(ControlChar.LF, LINE_KEY);
        if (val.contains(LINE_KEY)){
            String[] split = val.split(LINE_KEY);
            List<String> keys = new ArrayList<>();
            for (int i = 0; i < split.length; i++) {
                String newKey = MessageFormat.format("{0}_{1}",nodeKey,i);
            node.getRange().replace(nodeKey, StringUtils.join(keys,""), findReplaceOptions);
            for (int i = 0; i < split.length; i++) {
                String newKey = MessageFormat.format("{0}_{1}",nodeKey,i);
                String v = split[i];
                FindReplaceOptions thisOptions = new FindReplaceOptions();
                if(i != 0){
                    thisOptions.setReplacingCallback(new CustomReplaceEvaluator());
                node.getRange().replace(newKey, v, thisOptions);
        } else {
            node.getRange().replace(nodeKey, repVal, findReplaceOptions);
     * 插入换行符回调
    private static class CustomReplaceEvaluator implements IReplacingCallback {
        public int replacing(ReplacingArgs e)  {
            Document document = (Document) e.getMatchNode().getDocument();
            DocumentBuilder builder = new DocumentBuilder(document);
            Node currentNode = e.getMatchNode();
            return ReplaceAction.REPLACE;


It is great that you were able to resolve the problem on your end. In case you have further inquiries or may need any help in future, please let us know by posting a new thread in Aspose.Words’ forum.