【问题标题】:Salesforce extract substring from string with regexSalesforce 使用正则表达式从字符串中提取子字符串
【发布时间】:2015-08-19 16:47:58
【问题描述】:

我正在使用ApexSalesforce 中开发应用程序,我需要从其他string 中提取Substring。这是原String

String str = 'Product: Multi Screen Encoder Version: 3.51.10 (008) Order Number: 0030000a9Ddy Part Number: 99-00228-X0-Y-WW02-NA01 Comment: some comments';

我想提取Part Number的值,所以我使用MatcherPattern classes

Pattern p = Pattern.compile('Part Number: (.+)\\s');
Matcher pm = p.matcher(str);    
if (pm.matches()) {
    res = 'match = ' + pm.group(1);
    System.debug(res);
} else {
    System.debug('No match');
}

但我收到了No match

如何修复regex 以正确匹配我的String

【问题讨论】:

    标签: regex string salesforce match apex


    【解决方案1】:

    您需要在if 条件中使用find 函数而不是matches

    Pattern p = Pattern.compile('Part Number: (\\S+)\\s');
    Matcher pm = p.matcher(str);    
    if (pm.find()) {
        res = 'match = ' + pm.group(1);
        System.debug(res);
    } else {
        System.debug('No match');
    }
    

    \\S+ 匹配一个或多个非空格字符。

    Pattern p = Pattern.compile('Part Number: (.+?)\\s');
    

    【讨论】:

    • 感谢您的回答。我尝试了第一个命题,效果很好。我在我的问题中忘记了我还需要匹配Version,但它有空格。我如何提取值:3.51.10 (008)。 ??
    • @ihssan 这是一个困难的部分,因为键也包含空格。
    • 你可以试试Pattern p = Pattern.compile('Version: (\\d+(?:\\.\\d+)+(?:\\s\\([^)]*\\))?)');
    猜你喜欢
    • 2010-10-14
    • 1970-01-01
    • 1970-01-01
    • 2014-10-17
    • 2014-08-25
    • 2021-09-25
    • 1970-01-01
    • 2023-02-09
    相关资源
    最近更新 更多