4

I use Rubular to test my regular expressions, when I need them. I am having a bit of trouble crafting an expression that will work for me. For reference, I am trying to match multiple substrings in any order. My problem, however, is that I cannot get the dot (.) character to match newline characters.

I learned here that you can merge in options at the beginning of an expression using (?[options]), so I assumed (?m) would help me here. However, it does not seem to work:

Pattern keyword = Pattern.compile('(?mi)(?=.*\\bjack\\b)(?=.*\\bjill\\b)');
system.debug(keyword.pattern()); //(?mi)(?=.*\bjack\b)(?=.*\bjill\b)

system.assert(keyword.matcher('jack n jill').find(); // works
system.assert(keyword.matcher('jill n jack').find(); // works
system.assert(keyword.matcher('Jack n Jill').find(); // works
system.assert(keyword.matcher('jack \n jill').find(); // fail

However, it seems to me that this approach should work.

6

Different languages use different flags to control inline behavior. I gather that Ruby uses m to make dot match newline, but in Apex (and most other languages too, I think) you would want to use the s modifier flag to get this behavior.

Many languages use m to mean multi-line: The ^ and $ anchors now match at the beginning/end of each line respectively, instead of beginning/end of the entire string.
and s to mean single-line: The dot (.) metacharacter will with this flag enabled also match new lines.

Btw, my personal favorite Regex tester is Regex101

  • Interesting. Just curious, do you have a reference to back this up? That would make this answer more helpful for me, and more credible too! – Adrian Larson Mar 15 '16 at 16:52
  • I just added a link to the online regex tester that I use, which includes descriptions of all modifier flags – RenegadeCoder Mar 15 '16 at 16:54
  • Wow, I'd give you another +1 just for the link if I could. Amazing tool. Already bookmarked. – Adrian Larson Mar 15 '16 at 16:57
  • 1
    Note: You'll want to read the Pattern Java documentation, upon which Apex Code runs under. s enables the DOTALL flag (which allows . to match newline characters), while m only alters the effect of ^ and $ at the beginning/end of the line. – sfdcfox Mar 15 '16 at 19:11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.