Making regex case-insensitive

  • I have created some lines of code for an email handler that will scrape my emails for a particular string (STA0123).


      // Find STA No. (in email body)
      Opportunity Opp = [SELECT id, STA_No__c Opportunity WHERE Id =];
      String staNo = email.plainTextBody;
      Pattern staPattern = Pattern.compile('STA[0-9]{4}');
      Matcher matcherSta = staPattern.matcher(staNo);
      if (matcherSta.find())
        Opp.STA_No__c =;

    This works as expected but only with the first part of the string in capitals, STA0123 matches the pattern but sta0123 does not.

    Have you tried something like `Pattern.compile('[s|S]{1}[t|T]{1}[a|A]{1}[0-9]{4}');`?

  • Sergej Utko

    Sergej Utko Correct answer

    7 years ago

    You need to use JAVA-like CASE_INSENSITIVE pattern (?i)

    Something like this:

    Pattern staPattern = Pattern.compile('(?i)STA[0-9]{4}');

    I saw that pattern from java, wasn't sure whether it's applicable to APEX :). Good catch!

    It's also worth noting that you can re-apply case sensitivity within the expression using `(?-i)`. Any part of the expression to the right of `(?i)` will be case insensitive and anything to the right of `(?-i)` will be case sensitive.

License under CC-BY-SA with attribution

Content dated before 7/24/2021 11:53 AM