Domanda

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

È stato utile?

Soluzione

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.

Altri suggerimenti

^ 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

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top