Is there a way with Regex to grab the first word and replace a quoted section?

后端 未结 2 1776
遇见更好的自我
遇见更好的自我 2021-01-27 13:45

I\'m trying to replace ACACIA_BOAT (just a placeholder when copying things) with the first word, that being the variable name.

SCAFFOLDING = new         


        
2条回答
  •  逝去的感伤
    2021-01-27 14:03

    I do not use IntelliJ and therefore I can not comment on its settings. However, since you have asked for a regex solution, given below is the one:

    import java.util.Arrays;
    
    public class Main {
        public static void main(String[] args) {
            // Test strings
            String[] arr = { "SCAFFOLDING = new ItemBuilder(Material.valueOf(\"ACACIA_BOAT\")).build();",
                    "SEAGRASS = new ItemBuilder(Material.valueOf(\"ACACIA_BOAT\")).build();",
                    "SKULL_BANNER_PATTERN = new ItemBuilder(Material.valueOf(\"ACACIA_BOAT\")).build();" };
    
            String regex = "(([A-Za-z]\\w*)(?=\\s*\\=).*)(ACACIA_BOAT)(.*)";
    
            for (int i = 0; i < arr.length; i++) {
                arr[i] = arr[i].replaceAll(regex, "$1$2$4");
            }
    
            // Display the strings after replacement
            Arrays.stream(arr).forEach(System.out::println);
        }
    }
    

    Output:

    SCAFFOLDING = new ItemBuilder(Material.valueOf("SCAFFOLDING")).build();
    SEAGRASS = new ItemBuilder(Material.valueOf("SEAGRASS")).build();
    SKULL_BANNER_PATTERN = new ItemBuilder(Material.valueOf("SKULL_BANNER_PATTERN")).build();
    

    Explanation of the regex:

    1. The regex consists of 4 capturing groups:
      • group(1) is (([A-Za-z]\w*)(?=\s*\=).*) which is defined as a string starting with an alphabet (i.e. [A-Za-z]) followed by any number of word characters (i.e. a word character denoted by \w can be anything from [A-Za-z0-9_]) with the assertion (defined by the Positive Lookahead, (?=\s*\=)) that this all should be followed by an = symbol. The assertion does not become part of the selection. Note that there can be any number of space before the = symbol and it has been defined as \s* where * specifies zero or more times quantifier. The regex continues to select any character (specified by .*) after the = symbol.
      • group(2) is ([A-Za-z]\w*) which is already explained above. Note that this will capture just the variable name e.g. SCAFFOLDING.
      • group(3) is (ACACIA_BOAT) which matches ACACIA_BOAT literally.
      • group(4) is (.*) which matches any character
    2. The replacement string consists of group(1) + group(2) + group(4) specified by $1$2$4.

    Check this for a demo and more explanation of the regex.

提交回复
热议问题