首页 > 解决方案 > 如何使用正则表达式从字符串中提取子字符串

问题描述

代码我想要这种格式的正则表达式,如果匹配当前格式,则过滤掉 123456

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

我们必须从字符串 notes__c 字段中过滤子字符串。我的正则表达式只适用于PO #123456P.O. #123456

    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;
    }

标签: regexregex-lookarounds

解决方案


以上代码不工作的朋友

我已将我的代码修改为

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;
        }
      } 

它涵盖了除第一个 PO # 123456 之外的所有内容


推荐阅读