2

Im trying to get the hang of pattern and matcher. This method should use the regex pattern to iterate over an array of state capitals and return the state or states that correspond to the pattern. The method works fine when I check for whole strings like "tallahassee" or "salt lake city" but not for something like "^t" what is it that im not getting?

This is the method and main that calls it:

public ArrayList<String> getState(String s) throws RemoteException 
{
    Pattern pattern = Pattern.compile(s);
    Matcher matcher; 
    int i=0;
    System.out.println(s);
    for(String ct:capitalValues)
    {
        matcher = pattern.matcher(ct);
        if(ct.toLowerCase().matches(s))
            states.add(stateValues[i]);
        i++;    
    }
    return states;
}

public static void main (String[] args) throws RemoteException
{
    ArrayList<String> result = new ArrayList<String>();
    hashTester ht = new hashTester();

    result = ht.getState(("^t").toLowerCase());
    System.out.println("result: ");
    for(String s:result)
        System.out.println(s);


}

thanks for your help

2 Answers 2

3

You're not even using your matcher for matching. You're using String#matches() method. Both that method and Matcher#matches() method matches the regex against the complete string, and not a part of it. So your regex should cover entire string. If you just want to match with a part of the string, use Matcher#find() method.

You should use it like this:

if(matcher.find(ct.toLowerCase())) {
    // Found regex pattern
}

BTW, if you only want to see if a string starts with t, you can directly use String#startsWith() method. No need of regex for that case. But I guess it's a general case here.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for pointing this out, I looked at a lot of examples but just couldnt wrap my head around setting up the Pattern and Matcher syntax properly. This makes total sense now that I can successfully apply it. Thanks again.
0

^ is an anchor character in regex. You have to escape it if you do not want anchoring. Otherwise ^t mens the t at the beginning of the string. Escape it using \\^t

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.