[SalesForce] Unable to use multiline with pattern

I'm trying to match a string with Pattern/Matcher, however it is failing because I cannot set Pattern.MULTILINE like the Java documentation uses.

String testString = 'Line 1: Does not match\nCustomer Name: Bob Dole';
String regex = '^\\s*Customer Name\\s*:\\s+(.*)$';

Matcher m = Pattern.compile(regex).matcher(testString);
Boolean hasMatch = m.matches();  //Returns false

According to the Java documentation linked from the Pattern documentation on SFDC this should work:

Matcher m = Pattern.compile(regex, Pattern.MULTILINE).matcher(testString);

However, this gives the error Variable does not exist: Pattern.MULTILINE

Any ideas on how to get multiline working with Pattern?

Best Answer

You can use the mode modifier (?m) at the beginning of your regex pattern to specify the multiline option.

String testString = 'Line 1: Does not match\nCustomer Name: Bob Dole';
String regex = '(?m)^\\s*Customer Name\\s*:\\s+(.*)$';

Matcher m = Pattern.compile(regex).matcher(testString);

// iterate through testString finding subsequent matches
while (m.find()) {
    system.debug(m.start() + ': ' + m.group());
}

Debug output:

DEBUG|23: Customer Name: Bob Dole

There are a few other helpful option modifiers that can be used with the regex pattern at the beginning of the string: regular-expressions.info - Using Regular Expressions in Java

Related Topic