How to extract a substring from string in salesforce

Substring Format

PO # 123456
PO# 123456
PO #123456
P.O. # 123456
P.O.# 123456
P.O. #123456

We have to filter substring(123456) from string notes__c field and put it in test__c Field. I have used Regex in trigger it is covering everything except First one PO # 123456

MY CODE

if(oOrder.Notes__c != null) {
        Pattern p = Pattern.compile('PO # (\\S+)\\s');
        Pattern q = Pattern.compile('PO# (\\S+)\\s');
        Pattern r = Pattern.compile('PO #(\\S+)\\s');
        Pattern s = Pattern.compile('P.O. # (\\S+)\\s');
        Pattern t = Pattern.compile('P.O.# (\\S+)\\s');
        Pattern u = Pattern.compile('P.O. #(\\S+)\\s');
        Matcher pm = p.matcher(oOrder.Notes__c);
        Matcher qm = q.matcher(oOrder.Notes__c);
        Matcher rm = r.matcher(oOrder.Notes__c);
        Matcher sm = s.matcher(oOrder.Notes__c);
        Matcher tm = t.matcher(oOrder.Notes__c);
        Matcher um = u.matcher(oOrder.Notes__c);

        system.debug('find = ' +pm.find()); 
        if (pm.find()){
          string res =  pm.group(1);
          oOrder.test__c = res;
        } 
        if(qm.find()){
          string res1 =  qm.group(1);
          oOrder.test__c = res1;
        }
        if(rm.find()){
          string res2 =  rm.group(1);
          oOrder.test__c = res2;
        }
        if(sm.find()){
          string res3 =  sm.group(1);
          oOrder.test__c = res3;
        }
        if(tm.find()){
          string res4 =  tm.group(1);
          oOrder.test__c = res4;
        }
        if(um.find()){
          string res5 =  um.group(1);
          oOrder.test__c = res5;
        }
      } 

If there is any other way(Like strings methods) please suggest

728x90

1 Answers How to extract a substring from string in salesforce

You might use a single regex to capture the digits in a group:

(?<!\\S)P(?:O|\\.O\\.)\\h*#\\h*(\\d+)

Regex demo

Explanation

  • (?<!\S) Negative lookbehind to assert what is on the left is not a non whitespace character
  • P Match literally
  • (?:O|\.O\.) Match O or .O.
  • \h* Match zero or more times a horizontal whitespace
  • # Match literally
  • \h* Match zero or more times a horizontal whitespace
  • (\d+) Capture 1+ digits in a group

Demo

4 months ago