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

1 Answer 1

4

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

You must log in to answer this question.

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