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 = :matcher.group(0)];
  String staNo = email.plainTextBody;
  Pattern staPattern = Pattern.compile('STA[0-9]{4}');
  Matcher matcherSta = staPattern.matcher(staNo);
  if (matcherSta.find())
    Opp.STA_No__c = matcherSta.group(0);

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}');? Sep 16, 2014 at 11:43

3 Answers 3


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

Something like this:

Pattern staPattern = Pattern.compile('(?i)STA[0-9]{4}');
  • 1
    I saw that pattern from java, wasn't sure whether it's applicable to APEX :). Good catch! Sep 16, 2014 at 11:50
  • 6
    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.
    – JonM
    Sep 16, 2014 at 13:42

To make it case insensitive, you can just modify your pattern as follows

   Pattern staPattern = Pattern.compile('[Ss][Tt][Aa][0-9]{4}');

This can be long winded if you have a long pattern, so then you use the ignore case modifier

 Pattern staPattern = Pattern.compile('(?i)sta[0-9]{4}');
  • Apologies I thought it was my answer I'm editing :)... Reverting back! Sep 16, 2014 at 11:51

Pattern.compile('[s|S]{1}[t|T]{1}[a|A]{1}[0-9]{4}'); should do the trick. Basically what this does is:

Find the letter "S" either lower or upper case (only 1), followed by the same rule for the letter "T" and "A", then followed by any digit (4 times).

I've tested this and it worked for all possible combinations:


You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .