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

public class test_regex {

	public static void main(String[] args)
	{
		String text = "(asdf) (123) (zxcv)";
			
		Pattern p = Pattern.compile("^\\((\\S+)\\) \\((\\S+)\\) \\((\\S+)\\)$");
		Matcher m = p.matcher(text);
		
		if (m.matches())
			for (int i=0; i<m.groupCount(); i++)
				System.out.println(i+".) "+m.group(i)); 
		else
			System.out.println("no match");
	}
	
}

Output:
0.) (asdf) (123) (zxcv)
1.) asdf
2.) 123

I want my pattern to output:
0.) asdf
1.) 123
2.) zxcv

It seems like my pattern is taking the first ( and last ) to match the first pattern to the entire text. Is there any way to limit this type of regex to do as I want it to?

1
Contributor
1
Reply
2
Views
6 Years
Discussion Span
Last Post by TheWhite
0

oh shoot. nm. group 0 is the entire txt and m.groupCount() needs a +1 to show all the groups in the for loop. my mistake :)

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.