Below is the code :
String title = '(AB - QWER) Manager';
String titlePrefix = '(CD - DASF)';
String regex = '^(\\([A-Z][A-Z] - [A-Z][A-Z][A-Z][A-Z]\\))$';
if(title != null && !title.startsWith(titlePrefix)) {
//Get the prefix from the title
String[] parts;
String prefix = '';
parts = title.split('\\)',2);
if(parts.size() > 0 ) {
prefix = parts[0] + ')';
}
Pattern TitlePattern = Pattern.compile(regex);
Matcher prefixMatcher = TitlePattern.matcher(prefix);
System.debug('prefixMatcher::'+prefixMatcher.matches());
if(prefixMatcher.matches()){
prefix=titlePrefix;
title = title.replaceFirst(regex, prefix);
System.debug('Prefix0::'+prefix);
System.debug('NewTitle::'+ title);
}
}
I am trying to update the prefix of the title to the titlePrefix using replaceFirst Function, but it doesn't work. My End Result should be : title = '(CD - DASF) Manager'
title.split('\\)')
?)
and then rebuild the string with your replacement prefix + the part of the string after the)
?