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).

Code:

  // 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.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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

Something like this:

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

Method 2

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}');

Method 3

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:

STA1234
sTa1234
sta1234
...


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x