java - 查找并替换字符串模式 N 次,其中 N 在模式中定义

标签 java regex

我正在处理来自纯文本消息 (HL7) 的文本格式并重新格式化以供显示。一个例子是 \.sp5\。这意味着要插入五个换行符。

所以我想我会想做这样的事情:

Pattern.compile("\\\.sp(\d+)\\").matcher(retval).replaceAll("\n{$1}");

我的 IDE 告诉我在 \d 处有一个无效的转义序列,我不确定 replaceAll 参数是否符合我的预期。我认为正则表达式描述的是“反斜杠点 s p 一位或多位反斜杠”,我希望替换为“放入 $1 换行符”。

我怎样才能做到这一点?

解决方案是以下两位评论者的组合:

Pattern verticalSpacesPattern = Pattern.compile("\\\\\\.sp(\\d+)\\\\", Pattern.MULTILINE);
Matcher verticalSpacesMatcher = verticalSpacesPattern.matcher(retval);

while (verticalSpacesMatcher.find()) {
    int lineBreakCount = Integer.parseInt(verticalSpacesMatcher.group(1));
    String lineBreaks = StringUtils.repeat("\n", lineBreakCount);
    String group = verticalSpacesMatcher.group(0);
    retval = StringUtils.replace(retval, group, lineBreaks);
}

最佳答案

使用这个:

public static void main(String[] args) throws Exception {
            // Create a pattern to match comments
            Pattern p = 
                Pattern.compile("\\\\.sp(\\d+)", Pattern.MULTILINE);

            // Get a Channel for the source file
            File f = new File("Replacement.java");
            FileInputStream fis = new FileInputStream(f);
            FileChannel fc = fis.getChannel();

            // Get a CharBuffer from the source file
            ByteBuffer bb = 
                fc.map(FileChannel.MAP_RO, 0, (int)fc.size());
            Charset cs = Charset.forName("8859_1");
            CharsetDecoder cd = cs.newDecoder();
            CharBuffer cb = cd.decode(bb);

            // Run some matches
            Matcher m = p.matcher(cb);
     int i = 0;
    int n=0;
            while (m.find())
                n= Integer.parseInt(m.group(1));  //first group,0, is the whole string , 1 is the subgroup
     for(i=0;i<n;i++)
                System.out.println("\n");   
     }

关于java - 查找并替换字符串模式 N 次,其中 N 在模式中定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5318143/

相关文章:

Java - TCP - 多线程服务器 - 如何处理多个客户端连接?

regex - 如何在unix中对编号的文本文件进行排序?

regex - 连续替换 CSV 文件中的空值

regex - 如何预编译正则表达式?

java - Java 泛型和集合的问题

java - CodenameOne 中 List 中的组件

java - Struts 排除带有 Spring 的图案

java - 循环调用 SwingUtilities.invokeAndWait

javascript - 正则表达式匹配以问号结尾的短语

regex - 正则表达式检查用户输入模式