Question

I have the following regex to look for emails in a string(there might be 0 or more emails in the string).The expression has 4 groups,some of which could match a null value:

RegexPlanet Test for the expression:

          ([-A-Za-z0-9._!#$%^&*|{}'~`]+@[a-z0-9_-]+[\\.][a-z]{2,3}[\\.][a-z]{2,3})|([A-Za-z0-9.!#$%^&*|{}\"~`]+@[a-z0-9_-]+[\\.][a-z]{4})|([A-Z.a-z0-9!#$%^&*|{}'~`]+@[a-z0-9_-]+[\\.][a-z]{3})|([A-Za-z0-9.!#$%^&*_-|{}'~`]+@[a-z0-9_-]+[\\.][a-z]{2})

The code to read the data from the matcher shows an ArrayOutOfBoundsException at matchValue=matcher.group(i);

   ArrayList<String> result=new ArrayList<String>();
    Pattern pattern=Pattern.compile(regex);
    Matcher matcher=pattern.matcher(input);
    Log.d(TAG,"input: "+input);
    while(matcher.find())
    {
        String matchValue=null;
        for(int i=1;i<5;i++)
        {
            matchValue=matcher.group(i);
            if(matchValue!=null && !matchValue.equals(""))
            {    
                Log.d(TAG, "Group no: "+i+" Value: "+matchValue+" adding to result");
                result.add(matchValue);
            }
            else
            {
                Log.d(TAG, "Nothing matched for group i");
            }
        }    
    }
    return result;
}

Is there something wrong with the code or is this a side-effect of something else?

Thanking you in advance for your valuable suggestions

Was it helpful?

Solution 2

Try this:

for(int i=1; i <= matcher.groupCount(); i++)
{
    matchValue=matcher.group(i);
    ...

I am not sure why you would have a problem with the code you have, it seems to have exactly four groups, so for(int i=1; i<5; seems correct. But it is better to have the matcher tell you what the count is.

OTHER TIPS

Do you know what input causes the exception? In general to avoid this exception you can rewrite for loop as this:

for(int i=1;i<=matcher.groupCount();i++)
        {....}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top