0

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.

2
  • m.matches() == false even though m.groupCount() = 1 Commented Apr 27, 2010 at 19:17
  • I guess the JavaDoc should mention that the value returned from Matcher.groupCount is only valid if Matcher.find() returns true? Commented Apr 27, 2010 at 19:32

2 Answers 2

3

Try calling

m.find();

after the .matcher statement.

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

1 Comment

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!
1

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

3 Comments

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.
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
I did up-vote your response because you were correct in that I had a flaw in my code.

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.