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.

user396672
  • 3,106
  • 1
  • 21
  • 31
CDSO1
  • 297
  • 3
  • 11

2 Answers2

3

Try calling

m.find();

after the .matcher statement.

kennytm
  • 510,854
  • 105
  • 1,084
  • 1,005
  • 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 Apr 27 '10 at 19:24
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

Michael Mrozek
  • 169,610
  • 28
  • 168
  • 175
  • 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 Apr 27 '10 at 19:20
  • 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 Apr 27 '10 at 19:22
  • I did up-vote your response because you were correct in that I had a flaw in my code. – CDSO1 Apr 27 '10 at 19:28