3

I have this field that gets populated by an external service and I want to extract the number values from it then sum the numbers up. For instance, see the text below

United Kingdom: 3, Ireland: 1, Netherlands: 1, Spain: 2, Australia: 1

I would like to extract 3,1,1,2,1 and sum them individually to have 8. i.e. 3+1+1+2+1 = 8.

Thanks.

1
  • Can this be populated endlessly? without going to details, if you use text box you are limited to 256, why not use related list (custom abjectize this field) and easy summary the field to sum ? – Saariko Mar 14 '13 at 11:51
0

I would tackle this with a trigger and regular expressions. A regular expression along the lines of \\d+ (assuming integers) could be used to match the numbers in the text field; if the numbers are decimal you may need something more like \\d+\\.?\\d+ (any number of integers, an optional decimal point, and then more integers.) You would then iterate through the set of the matches to sum the values.

Since Apex uses Java regular expressions you should be able to find many tutorials on the specifics.

Note: These regexes have not been tested and will probably need to be tweaked to suit your needs.

3
  • 1
    This Code helped! LinkedList<String> numbers = new LinkedList<String>(); Pattern p = Pattern.compile("\\d+"); Matcher m = p.matcher(line); while (m.find()) { numbers.add(m.group()); } – Kenn K Mar 13 '13 at 20:54
  • Glad to have helped, @KennK. – Mike Chale Mar 14 '13 at 11:00
  • By the way, if this answered your question please mark it as the answer and vote it up. – Mike Chale Mar 14 '13 at 11:37
0

As long as the syntax/format of the string is guaranteed meaning as long comma is the separator between countries and colon is the separator between number values, then in a simple method, I would probably split by comma. Assuming comma is the delimiter then grab the number by looking for the first index of space searching backwards just sum them up as required.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.