views:

131

answers:

2

Below is an example that is producing an exception in Java (and not matching the input). Perhaps I misunderstood the JavaDoc, but it looks like it should work. Using the same pattern and input in C# will produce a match.

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Main { 
    public static void main(String[] args) {
        String pattern = "aspx\\?uid=([^']*)";      
        Pattern p = Pattern.compile(pattern);
        Matcher m = p.matcher("id='page.aspx?uid=123'");
        System.out.println(m.groupCount() > 0 ? m.group(1) : "No Matches");     
    }
}

EDIT: I should note the JavaDoc says the following about Matcher.groupCount

Any non-negative integer smaller than or equal to the value returned by this method is guaranteed to be a valid group index for this matcher.

+1  A: 

It's throwing an exception because the pattern didn't match but you tried to get a group from it (m.matches() would be false here); groupCount() will return the number of groups that would be in a match, regardless of if there actually was one. As for why the match isn't working, Java Patterns match on the entire string, not on a substring

Michael Mrozek
Thank you for pointing out the flaw in the code that is causing the exception. However, I am still not clear on your last statement. The pattern SHOULD produce a match. It does not. I know that there is a reason, and I was hoping I could get an explaination, as well as possibly a fix for my expression. Appreciated.
CDSO1
It's what I said; Patterns match on the whole string. Thus the pattern "a" will not match the string "ba", but the pattern ".a" will. You can use `Matcher.find()` to get around that, as [KennyTM said](http://stackoverflow.com/questions/2724222/java-regex-pattern-not-matching-works-in-net/2724274#2724274)
Michael Mrozek
I did up-vote your response because you were correct in that I had a flaw in my code.
CDSO1
+3  A: 

Try calling

m.find();

after the .matcher statement.

KennyTM
Well, that explains it. The example actually left out the find, but going back and looking at the original code that raised the issue for me, find() was only called during a specific condition. Thank you!
CDSO1