Thursday, May 04, 2006

Nobody must use Java Regular Expressions

I'm having a hell of a time converting some Python regex's to Java (first rule, you have to double escape everything) and I'm still getting a bunch of nasty exceptions, the "Illegal repetition" error in particular :(

Yes, I'm weak, but once you use Visual C# it is hard to go back.


package regextest;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main {
public Main() {
}
public static void main(String[] args) {
// Pattern p = Pattern.compile("^\\[char\\speer[\\d+]_[\\d+]*");
// packet = re.compile(r"^char\speer(\d)_(\d+)\[.*{(.+)};$")
Pattern p = Pattern.compile("^\\[char\\speer(\\d)_(\\d+).*$");
Pattern p1 = Pattern.compile(".*\\{(.*)\\};");
Matcher m = p.matcher("[char peer1_2[] = {, 0x03, 0x00, 0x00,
0x31, 0x02 0x5f, 0x53, 0x50, 0x50, 0x31, 0x5f, 0x50, 0x41 };");
Matcher m1 = p1.matcher("[char peer1_2[] = {, 0x03, 0x00,
0x00, 0x31, 0x02 0x5f, 0x53, 0x50, 0x50, 0x31, 0x5f, 0x50, 0x41 };");

if ( m.matches()) {
if ( m.groupCount() > 0 ) {
System.out.println(m.group(1));
System.out.println(m.group(2));
}
} else {
System.out.println("No match");
}

if (m1.matches()) {
System.out.println(m1.group(1));
} else {
System.out.println("You suck!");
}
}
}

No comments: