tags:

views:

108

answers:

2

I have this regex to test for telephone # that should be a toll free.

public static final Pattern patternTollFree = Pattern.compile("^((877)|(800)|(866)|(888))");

So I only want to get those # where the user may have left the 1 off of the front of the string, but I have tried several things and I can't get java to match.

public String changeRingTo( String changedRinger )
{
    if ( null == changedRinger || changedRinger.length() != 10)
        return changedRinger;
    if ( patternTollFree.matcher(changedRinger).region(0, 2).matches() )
        changedRinger = '1' + changedRinger;
    return changedRinger;
}

I can't get this 2nd test case below to succeed. What am I doing wrong?

assertEquals( "Regex not working", "8189091000", of.changeRingTo("8189091000"));
assertEquals( "Regex not working", "18769091000", of.changeRingTo("8769091000"));
+1  A: 

The second argument to region is exclusive, not inclusive. Right now you are only allowing it to check the first two characters of the input. You need to change it to

if ( patternTollFree.matcher(changedRinger).region(0, 3).matches() )

See http://java.sun.com/javase/6/docs/api/java/util/regex/Matcher.html#region%28int,%20int%29

Note that it is redundant to use ^ in your regex and also specify the region on your matcher.

danben
+1  A: 

Your second test case fails because it starts with 876 which is not a valid toll free prefix. Additionally, as indicated in the other answer, you should change region(0, 2) to region(0, 3) although that entire line could be significantly simplified.

Asaph
Thanks, I can't believe I missed that. That was the whole problem. How could it be simplified? 8((66)|(77))
arinte
@arinte: Change it to `if (changedRinger.matches("^(877|800|866|888)\\d+$"))` and get rid of the `patternTollFree` variable entirely.
Asaph
If you precompile your pattern it is supposed to have better performance.
arinte
@arinte: Is that kind of micro-performance difference significant in your application? If not, I would opt for readability over performance.
Asaph