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)

Thanks!
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);
                //替换
                keys.add(newKey);
            }
            //占位符替换一遍
            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 {
        @Override
        public int replacing(ReplacingArgs e)  {
            Document document = (Document) e.getMatchNode().getDocument();
            DocumentBuilder builder = new DocumentBuilder(document);
            Node currentNode = e.getMatchNode();
            //将光标移动到此位置
            builder.moveTo(currentNode);
            //插入换行符
            builder.insertBreak(BreakType.LINE_BREAK);
            return ReplaceAction.REPLACE;
        }
    }

@ghsoft,

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.