Here is a string of length 60 which in turn could be divided into 10 individual strings of 6 characters each . I want to divide this(6 character string) into a pattern of 3-2-1. I want to use Regular expression. jdk is 1.4.2 String regex = "((\\w|\\s){3})((\\w|\\s){2})((\\w|\\s){1})" The string could be made of white spaces or characters Here is the java class import java.util.regex.Matcher; import java.util.regex.Pattern; public class RegexTest { private static String input; private static Pattern pattern; private static Matcher m; public static void main( String args []) { String regex = "((\\w|\\s){3})((\\w|\\s){2})((\\w|\\s){1})"; input = "ABCDEFGHIJKLMNOPQURSTUVWXYZ" ; pattern = Pattern.compile(regex); m = pattern.matcher(input); while (m.find()) { System.out.println(m.group(0)); System.out.println(m.group(1)); System.out.println(m.group(2)); System.out.println(m.group(3)); } } }
The expected result is ABCDEF ABC DE F
Thanks in advance, mat [ October 12, 2005: Message edited by: k matthew ]
Alan Moore
Ranch Hand
Joined: May 06, 2004
Posts: 262
posted
0
Capturing groups are numbered according to the order in which their opening parentheses appear. You should have made those innermost groups non-capturing, like this:But a character class would be much more efficient than alternation there: [ October 13, 2005: Message edited by: Alan Moore ]