function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Patrick HanahanPatrick Hanahan 

In Apex code, how can I parse an incoming email subject for a 6 digit number that is different every time?

In most of the emails I recieve, the subject contains a 6 digit "job number", which designates which assignment the email is about. Many of these emails come from the same email address, so the job number is the only way I can associate an incoming email with a specific opportunity. 

Is there any way to parse each incoming email subject to look for a 6 digit code?
Best Answer chosen by Patrick Hanahan
Chad.PfrommerChad.Pfrommer
Use Regex with the Pattern and Matcher classes.  For example, here we're matching any 6 digit number in a string:
 
String regex = '\\b\\d{6}\\b';

List<String> inputs = new List<String> {
  'adfajsf 123456 asldkfjad',
  '234567',
  '342903402934',
  'asdfkasdjflal',
  'sjdf 838383alskdjf',
  '123 2354 25432 545454 8383838 83838383838'
};

Pattern p = Pattern.compile(regex);

for (String input : inputs) {
  System.debug('input string: ' + input);
  Matcher m = p.matcher(input);
  if (m.find()) {
    System.debug('matched: ' + m.group(0));
  } else {
    System.debug('no match');
  }
}

 

All Answers

Chad.PfrommerChad.Pfrommer
Use Regex with the Pattern and Matcher classes.  For example, here we're matching any 6 digit number in a string:
 
String regex = '\\b\\d{6}\\b';

List<String> inputs = new List<String> {
  'adfajsf 123456 asldkfjad',
  '234567',
  '342903402934',
  'asdfkasdjflal',
  'sjdf 838383alskdjf',
  '123 2354 25432 545454 8383838 83838383838'
};

Pattern p = Pattern.compile(regex);

for (String input : inputs) {
  System.debug('input string: ' + input);
  Matcher m = p.matcher(input);
  if (m.find()) {
    System.debug('matched: ' + m.group(0));
  } else {
    System.debug('no match');
  }
}

 
This was selected as the best answer
Patrick HanahanPatrick Hanahan
Thank you, that is very helpful. Is there any way I could turn the subject into a list with each word being an index, rather than all in one string? Or pull it into a string then separate it into a list?

 
Chad.PfrommerChad.Pfrommer
There's plenty of ways to do that.  Here's one option:

https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_methods_system_string.htm#apex_System_String_splitByCharacterTypeCamelCase