how to replace multiple matched Regex

后端 未结 2 1858
感情败类
感情败类 2021-01-03 07:11

I have a set of regex replacements that are needed to be applied to a set of String,

For example:

  1. all multiple spaces with single space (\"\\s{
2条回答
  •  有刺的猬
    2021-01-03 07:53

    Look at Replace multiple substrings at Once and modify it.

    Use a Map>.

    • group numbers as Integer keys
    • Lambdas as values

    Modify the loop to check which group was matched. Then use that group number for getting the replacement lambda.

    Pseudo code

    Map> replacements = new HashMap<>() {{
        put(1, matcher -> "");
        put(2, matcher -> " " + matcher.group(2));
    }};
    
    String input = "lorem substr1 ipsum substr2 dolor substr3 amet";
    
    // create the pattern joining the keys with '|'. Need to add groups for referencing later
    String regexp = "(\\s{2,})|(\\.(?:[a-zA-Z]))";
    
    StringBuffer sb = new StringBuffer();
    Pattern p = Pattern.compile(regexp);
    Matcher m = p.matcher(input);
    
    while (m.find()) {
        //TODO change to find which groupNum matched
        m.appendReplacement(sb, replacements.get(m.group(groupNum)));
    }
    m.appendTail(sb);
    
    
    System.out.println(sb.toString());   // lorem repl1 ipsum repl2 dolor repl3 amet
    

提交回复
热议问题