Tuesday, October 2, 2007

Simple LS2J Regular Expression class

A simple Regular Expression class. You may need to remove the line-breaks I've inserted to make it fit the width of the blog.

/*
Usage:
Uselsx "*javacon"
Use "whateverYouCallThisLS2J-class"
--
Dim js As JAVASESSION
Dim regexp As JAVACLASS

Set js = New JAVASESSION
Set regexp = js.GetClass("RegExp")

Print regexp.test("http://www.compendia.no",
".*compendia.*") -> True
Print regexp.split("test","e") -> "t,st"
Print regexp.replace("test pest hest",
"t\\w"," ", true) -> "tes pes hes"
*/

public class RegExp {
//test a string
public static boolean test(String streng, String expr){
return streng.matches(expr);
}
//returns a comma separated string
public static String split(String streng, String expr){
String temp[] = streng.split(expr);
if(temp.length == 0) return "";

String res = temp[0];
for(int i=1; i < temp.length; i++){
if(temp[i].length()==0) continue;
res += "," + temp[i];
}
return res;
}
//replace parts of a string
public static String replace(String streng,
String from, String to, boolean all){
return all ?
streng.replaceAll(from, to) :
streng.replaceFirst(from, to);
}

}

0 comments: