Formatting string using StringTokenizer

I have a string retrieved from a database such as

[[TO_CHAR(MIN(WEEK),'DD-MON-YYYY')], [30-OCT-2005]]

For some reason it prepends my sql query to the string so I'm using a StringTokenizer to remove all the useless stuff and retrieve the date

So far I have:

privatevoid formatDate(String thisString)

{

StringTokenizer st =new StringTokenizer(thisString,"[]");

while(st.hasMoreTokens()){

String token = st.nextToken();

logger.info(token);

if(token.startsWith("0-9") && token.endsWith("0-9")){

logger.info("token is " +token);

}

}

However the startsWith() and endsWith() methods are not called - what I'd like to do is just for it to check whether it starts/ends with any number without having to write a whole class to achieve this. This is possible, correct?

[1263 byte] By [Dhaval-Shaha] at [2007-10-3 3:10:41]
# 1

From the JavaAPI-docs:

StringTokenizer is a legacy class that is retained for compatibility reasons although its use is discouraged in new code. It is recommended that anyone seeking this functionality use the split method of String or the java.util.regex package instead.

Details about regex's Pattern class can be found here:

http://java.sun.com/j2se/1.5.0/docs/api/java/util/regex/Pattern.html

So you could do something like this:

String theString = "[[TO_CHAR(MIN(WEEK),'DD-MON-YYYY')], [30-OCT-2005]]";

String[] tokens = theString.split("\\[|\\]");

// This regex will match a string that starts with 2 numbers followed

// by a - (minus sign), then 3 capital letters, then a -, and ends with

// 4 numbers.

String regex = "[0-9]{2}-[A-Z]{3}-[0-9]{4}";

for(int i = 0; i < tokens.length; i++) {

String token = tokens[i];

if(Pattern.matches(regex, token)) {

System.out.println(token);

}

}

Good luck.

prometheuzza at 2007-7-14 21:01:29 > top of Java-index,Other Topics,Algorithms...
# 2

I suspect that using getDate() on the ResultSet might be best but if that does not work then this one line extraction might help

String theString = "[[TO_CHAR(MIN(WEEK),'DD-MON-YYYY')], [30-OCT-2005]]";

String date = theString.replaceAll(".*\\[([^\\]]+).*","$1");

sabre150a at 2007-7-14 21:01:29 > top of Java-index,Other Topics,Algorithms...