[SalesForce] How to snip and pass a string value between brackets to a Map

I've been searching through past questions and other literature to try to figure this out but it's time to just ask outright.

I'm trying to write an after insert trigger that takes the string value between the first encountered ( and ) in a text field, and passes it into a map for an ID return to be used in a new record creation.

I've experimented with patterns+matchers as well as indexOf code, without success. Could anyone assist with examples of either? Thanks.

Code I've begun (using the Event object):

for(Event e : trigger.new){
     String EDescription = Event.Description;
     String ExtractedString = EDescription.indexOf("(") + 1,   myString.lastIndexOf(")"));
}

et cetera…

I've also tried modifying the code found at Can anyone help with a formula to pull an email address from a text string in a standard field?

Namely:

for (Event e: Trigger.new) {
    if (e.Description != null) {
        Pattern StringPattern = Pattern.compile('(?i)^([A-Z0-9._%+-]+@[A-Z0-9.-]+\\.[A-Z]{2,4})$');
        for (String bit: e.Description.split(' ')) {
            Matcher StringMatcher = StringPattern.matcher(bit);
            if (StringMatcher.matches()) {
                e.Description_ExtractedString__c = bit;
            }
        }
    }
}

I've not yet modified the pattern-matcher RegEx code specifically enough but I believe the context is clear.

Best Answer

The code below will get the text from within the brackets. The code makes use of some String methods

String eDescription = 'This is (the test) text';
Integer openingIndex = eDescription.indexOf('(');
Integer closingIndex = eDescription.indexOf(')');
String textInBrackets = eDescription.subString(openingIndex + 1, closingIndex);

Using @Sovereigntys suggestion of using substringBetween then the code becomes:

String eDescription = 'This is (the test) text';
String textInBrackets = eDescription. substringBetween('(', ')');

FYI: Both ways will find the first instance of '(' and ')'.

  • Input: 'This is (the test) text', Output: 'the test'
  • Input: 'This is (the test) (text)', Output: 'the test'
Related Topic