I\'m trying to replace ACACIA_BOAT (just a placeholder when copying things) with the first word, that being the variable name.
SCAFFOLDING = new
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:
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 charactergroup(1) + group(2) + group(4) specified by $1$2$4.Check this for a demo and more explanation of the regex.