1

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

5

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));
  • Now it enters the If block . But cant return the substring. – Pranay Jaiswal Jun 23 '17 at 5:28
  • @PranayJaiswal You need to use group(0), because you haven't used any capture groups. – sfdcfox Jun 23 '17 at 5:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.