0

I'm trying to count the number of URLs in any given Java string:

String test = "Hello World!";
String urlRegex = "<\\b(https?|ftp|file)://[-a-zA-Z0-9+&@#/%?=~_|!:,.;]*[-a-zA-Z0-9+&@#/%=~_|]>";
pattern = Pattern.compile(urlRegex);
matcher = pattern.matcher(test);
numUrls = matcher.groupCount();
System.err.println("numUrls = " + numUrls);

I am surprised to see that numUrls is not zero. Any ideas as to why? Thanks in advance!

2
  • 4
    You need to use matcher.find(), there's always one group. Commented Mar 19, 2013 at 18:33
  • What if there are 6 URLs in the string? Commented Mar 19, 2013 at 18:36

1 Answer 1

0

From the javadoc for Matcher#groupCount()

Returns the number of capturing groups in this matcher's pattern.

Your pattern has one group ...(https?|ftp|file)... so it returns 1.

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

4 Comments

Hmmm good catch and +1 - so what do I need to use instead of groupCount?
Im trying to count the number of URLs in a Java string.
Loop on find() and use your own counter.
So like while(matcher.find()) numUrls++;?

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.