0

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'

5
  • You only actually do anything if the title contains multiple backslashes followed buy parentheses. Why are you checking title.split('\\)')?
    – Adrian Larson
    Commented May 6, 2021 at 13:45
  • @adrianlarson I am using title.split('\)') to get the prefix initial title string. Once I have it I am checking if the prefix I have obtained matches with the regex that I have defined and if matched then I want to replace it with the new prefix Commented May 6, 2021 at 13:48
  • 1
    why do you need the regex at all? can't you just split on the ) and then rebuild the string with your replacement prefix + the part of the string after the ) ?
    – cropredy
    Commented May 6, 2021 at 13:49
  • You don't need to escape parentheses when splitting a string. Trying to do so is throwing you off here.
    – Adrian Larson
    Commented May 6, 2021 at 13:57
  • @AdrianLarson Split uses a regex, so you actually do need to.
    – sfdcfox
    Commented May 6, 2021 at 14:33

1 Answer 1

1

Your solution is incredibly over-complicated.

You just need to write:

String title = '(AB - QWER) Manager';
String titlePrefix = '(CD - DASF)';
String regex = '^\\([A-Z]{2} - [A-Z]{4}\\)';
String output = title?.replaceFirst(regex, titlePrefix);
System.debug(output);

Where ?. is the Safe Navigation Operator (so, if null, it just returns null early), and ^\\([A-Z]{2} - [A-Z]{4}\\) matches (XX - XXXX) (where X is any letter), but only if it is at the beginning of the string (^). If the match is not found, the original string is returned.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .