regex - 如何使用正则表达式从字符串中提取子字符串
问题描述
代码我想要这种格式的正则表达式,如果匹配当前格式,则过滤掉 123456
PO # 123456
PO# 123456
PO #123456
P.O. # 123456
P.O.# 123456
P.O. #123456
我们必须从字符串 notes__c 字段中过滤子字符串。我的正则表达式只适用于PO #123456
和 P.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;
}
解决方案
以上代码不工作的朋友
我已将我的代码修改为
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 之外的所有内容
推荐阅读
- pandas - 将熊猫中的两个连续事件发生子集
- mysql - MySQL80服务自动停止
- flutter - 未处理的异常:类型 '_InternalLinkedHashMap
' 不是 'GeoPoint' 类型的子类型 - javascript - 将对象数组重构到更深层次
- ios - 动态 UITextView 大小 (Swift 4)
- microsoft-graph-api - 如何永久获取 OneDrive API 下载地址
- javascript - 在解决 sinon 时获得重复迭代,无法在 nodejs 中进行单元测试
- php - ElasticSearch - PHP - 抓取最后一个查询
- python - Pyodbc 未显示已安装的任何驱动程序
- reactjs - 反应的材料 UI 中的下拉列表替代方案