+ Start a Discussion
brijender singh rathore 16brijender singh rathore 16 

How to extract a substring from string using regex

I want regex for this format and filter out 123456 if match the current format
PO # 123456
PO# 123456
PO #123456
P.O. # 123456
P.O.# 123456
P.O. #123456

We have to filter substring from string notes__c field. my regex is only working for PO #123456 and P.O. #123456
tried PO# (\\S+)\\s not working
Matcher rm = r.matcher(oOrder.Notes__c); 
Pattern r = Pattern.compile('PO #(\\S+)\\s'); 

if(rm.find()) {
 string res2 = rm.group(1); 
oOrder.test__c = res2; 

NagendraNagendra (Salesforce Developers) 
Hi Brijendar,

The key thing to note here is the optional whitespace. Whitespace can appear before and/or after the #. Whenever you see a pattern like this, you usually need \s* (if you allow multiple whitespaces) or \s? (if you only allow one or more whitespace).
The first part can either be PO or P.O.. We can write these two alternatives with the | token. Remember to escape the .s.
The whole regex looks like this:
Here, I assumed the thing you want to capture matches \d+. If that part can contain letters, change the capture group accordingly.
To write the regex as a string literal, you need to escape the backslashes:
Hope this helps.

Kindly mark this as solved if the reply was helpful.

brijender singh rathore 16brijender singh rathore 16
thanks Nagendra  but i have tried your code but it is not working.
I have Modified the 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;
          string res1 =  qm.group(1);
          oOrder.test__c = res1;
          string res2 =  rm.group(1);
          oOrder.test__c = res2;
          string res3 =  sm.group(1);
          oOrder.test__c = res3;
          string res4 =  tm.group(1);
          oOrder.test__c = res4;
          string res5 =  um.group(1);
          oOrder.test__c = res5;

it is covering everything except 
PO # 123456