aspose file tools*
The moose likes Java in General and the fly likes Regular Expression with java Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of The Java EE 7 Tutorial Volume 1 or Volume 2 this week in the Java EE forum
or jQuery UI in Action in the JavaScript forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "Regular Expression with java" Watch "Regular Expression with java" New topic
Author

Regular Expression with java

k matt
Greenhorn

Joined: Oct 12, 2005
Posts: 22
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
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 ]
k matt
Greenhorn

Joined: Oct 12, 2005
Posts: 22
Thank you, it works.
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Regular Expression with java