[SalesForce] Find a Particular Substring using Regex

I am trying my hands on Email Services, am stuck at a place where I need to create a regex.

I want to find all substring which looks like "PIKA-170510-115943".

Here is my code.

String str='Strating text PIKA-170510-115943 Ending Text';
String regex='[A-Z]{4}-[0-9]{6}-[0-9]{6}';


Matcher matcher=Pattern.compile(regex).matcher(str);
Boolean result= matcher.find();

System.debug('result is : '+result);
if(result){
   System.debug('Matching string'+matcher.group(1));
}

The result is always true and when it enters the IF block it gives me .

EXCEPTION: System.StringException: Group index out of bounds (parameter 1): No group 1

Best Answer

matches matches the entire string against the Pattern (by default; you'll want to read more about Regions in the documentation). Instead, you'll want to use find:

Matcher matcher=Pattern.compile(regex).matcher(str);
Boolean result= matcher.find();

To read the matched string, use the zeroth group:

System.debug('Matching String: '+matcher.group(0));
Related Topic