简体   繁体   English

修复java中交错的正则表达式替换输出

[英]Fix staggered regex replace output in java

I am trying to get every regex match on its own line with commas in between each element in the line, I have tried to methods to this, but both times the results are staggered for some reason, I replaced the regex and output with a something simpler just to show it, for example the results would look like我试图将每个正则表达式匹配在自己的行上,并在行中的每个元素之间使用逗号,我已经尝试过对此的方法,但是由于某种原因两次结果都是交错的,我用一些东西替换了正则表达式和输出只是为了显示它更简单,例如结果看起来像

1 ,   , 
  , a ,
  ,   , b

when the results should be结果应该是什么时候

1 , a , b

With a new line for the next match为下一场比赛换一条新线

Here are both attempt I tried, this is java这是我尝试过的两种尝试,这是java

input.replaceAll("(1)|(a)|(b)" , "$1 , $2 , $3 \\n");

and

(match.group(1) + "," + match.group(2) + "," + match.group(3));

the file the is being parsed looks like this for example例如,正在解析的文件看起来像这样

1 a b

How would i fix the output so its not staggered ?我将如何修复输出,使其不交错?

As far as I can understand this could be of help:据我所知,这可能会有所帮助:

input.replaceAll("(1).*?(a).*?(b)" , "$1 , $2 , $3 \n");

All will be captured with one replace.所有将被捕获一次替换。

But please explain more what behavior do you expect, because that's not exactly clear, eg "with commas in between each element in the line"但是请解释更多您期望什么行为,因为这并不完全清楚,例如“在行中的每个元素之间使用逗号”

Here's a way to do it:这是一种方法:

import java.util.regex.*;

public class Test
{
     public static String process(String s)
     {
         Pattern p = Pattern.compile("1|a|b");
         Matcher m = p.matcher(s);
         StringBuilder sb = new StringBuilder();
         while(m.find())
         {
             if(sb.length()>0)
                sb.append(" , ");
            sb.append(m.group());
         }
         return sb.toString();
     }

     public static void main(String[] args)
     {
         System.out.println(process("1 a b"));
     }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM