0

I want to remove everything except for Name. removeStart() and remove() don't seem to take variable as a parameter.

String tmpField  = '{!Contract.Name}';

String child = 'Contract';

tmpField = tmpField.removeStart('{!'); // Works

tmpField = tmpField.remove(child); // Doesn't seem to work - remove() or removeStart()

tmpField = tmpField.removeStart('.');

tmpField = tmpField.removeEnd('}');

Please let me know if any other ways to achieve that.

1 Answer 1

2

for this kind of task regex is the best instrument to use. Here is a link to test regex for your needs. You can also read an explanation for regex:

"(!Contract.)(.*)(?=})"
    1st Capturing Group (!Contract.)
        !Contract matches the characters !Contract literally (case sensitive)
        . matches any character (except for line terminators)
    2nd Capturing Group (.*)
        . matches any character (except for line terminators)
        * matches the previous token between zero and unlimited times, as many times as possible, giving back as needed (greedy)
    Positive Lookahead (?=})
Assert that the Regex below matches
    } matches the character } with index 12510 (7D16 or 1758) literally (case sensitive)

Apex:

String objectToMatch = 'Contract';
String stringToFind = '{!Contract.Name}';
Pattern pat = Pattern.compile('(!' + objectToMatch + '.)(.*)(?=})');
Matcher mat = pat.matcher(stringToFind);
if(mat.find()){
    System.debug(mat.group(2));
}

Debug:

|DEBUG|Name


In this case, you can control for which object you need to parse a field from the input String.

12
  • The main problem I have is matching with a variable, and that didn't work for me when I tried removeStart() and remove(). I might have tried Regex already. I will give it another go and see.
    – ApexCowboy
    Oct 22, 2021 at 7:24
  • @ApexCowboy what do you mean by "matching with a variable" ? Can you update your question with another example, of what is an input and what should be as an output? the provided answer works correctly to get the field name. Oct 22, 2021 at 7:28
  • @ Oleksandr Berehovskyi Instead of matching with 'Contract', I want to match with a variable that contains the string 'Contract'. In my example, String child = 'Contract';
    – ApexCowboy
    Oct 22, 2021 at 7:31
  • @ApexCowboy I've updated the answer to parse field based on the object name. Please check. Oct 22, 2021 at 8:12
  • @ Oleksandr Berehovskyi Pattern pat = Pattern.compile('(\\{\\!Contract.)(.*)\\}'); works, but with variable Pattern pat = Pattern.compile('(\\{\\!'+ child +'.)(.*)\\}'); doesn't work for me.
    – ApexCowboy
    Oct 22, 2021 at 13:38

You must log in to answer this question.

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