troubleshooting Question

Understanding Greedy Quantifier * and +

Avatar of techbro
techbroFlag for United States of America asked on
Java
14 Comments2 Solutions297 ViewsLast Modified:
I ran these arguments given below:

[wow]* "wow its cool"
Output: 0 "wow" 3 "" 4 "" 5 "" 6 "" 7 "" 8 "" 9 "oo" 11 "" 12 ""

[wow]+ "wow its cool"
Output: 0 "wow" 9 "oo"

I know that * is a greedy quantifier which matches as many as it can and must be zero or more, so there are empty strings after "wow". But can you tell me the reason I got "oo" in the output for both + and *?

I find greedy quantifiers hard to understand. I know + means 1 or more, and * mean zero or more, but I am not sure under what situation I am supposed to use each of them?
Can you simplify the difference between them? (Any analogy or examples would helpful)


I used the code below to try those greedy quantifiers:

import java.util.regex.*;
public class TestClass
{
	public static void main(String[] args)
	{
		Pattern p = Pattern.compile(args[0]);
		Matcher m = p.matcher(args[1]);
		boolean b = false;
		while(b = m.find())
		{
		    System.out.print(m.start()+" \""+m.group()+"\" ");
		}
	}
}

Open in new window


I will appreciate your response.
ASKER CERTIFIED SOLUTION
Join our community to see this answer!
Unlock 2 Answers and 14 Comments.
Start Free Trial
Learn from the best

Network and collaborate with thousands of CTOs, CISOs, and IT Pros rooting for you and your success.

Andrew Hancock - VMware vExpert
See if this solution works for you by signing up for a 7 day free trial.
Unlock 2 Answers and 14 Comments.
Try for 7 days

”The time we save is the biggest benefit of E-E to our team. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange.

-Mike Kapnisakis, Warner Bros