const regex = /^(?<indent>\s*)(?<mod1>\w+)\s(?<mod2>\w+)?\s*(?<mod3>\w+)?\s*(?<return>\b\w+)\s(?<name>\w+)\((?<arg>.*?)\)\s*\{(?<body>.+?)^\k<indent>\}/mgs;
// Alternative syntax using RegExp constructor
// const regex = new RegExp('^(?<indent>\\s*)(?<mod1>\\w+)\\s(?<mod2>\\w+)?\\s*(?<mod3>\\w+)?\\s*(?<return>\\b\\w+)\\s(?<name>\\w+)\\((?<arg>.*?)\\)\\s*\\{(?<body>.+?)^\\k<indent>\\}', 'mgs')
const str = `public static FieldsConfig getFieldsConfig(){
if(xxx) {
sssss;
}
return;
}
public String getAsSeparateGroup(String groupName) {
String begin = pattern.substring(0,getStart());
String mid = pattern.substring(getStart(),getEnd());
String finish = pattern.substring(getEnd());
return begin + "(?<" + groupName + ">" + mid + ")" + finish;
}
@Override
public static final String toString() {
return asString;
}
public String directMatch(String match) {
Matcher matcher = Pattern.compile(getAsSeparateGroup("test")).matcher(match);
matcher.find();
String result;
try {
result = matcher.group("test");
}catch (Exception ex) {
result = "empty";
}
return getPattern() + ":" + result;
}
}`;
const subst = ``;
// The substituted value will be contained in the result variable
const result = str.replace(regex, subst);
console.log('Substitution result: ', result);
Please keep in mind that these code samples are automatically generated and are not guaranteed to work. If you find any syntax errors, feel free to submit a bug report. For a full regex reference for JavaScript, please visit: https://developer.mozilla.org/en/docs/Web/JavaScript/Guide/Regular_Expressions