Thursday, October 6, 2011

SCJP 6 Part VIII - Regex With Scanner

// split string by a dot
Scanner scanner = new Scanner("my.name.is.budi");
scanner.useDelimiter("\\.");
while (scanner.hasNext()) {
System.out.println(scanner.next());
}

result:

my
name
is
budi

// split string by regex (zero or one comma) and a space
Scanner scanner1 = new Scanner("1 isn't true, 0 isn't false, 2.0 is double");
scanner1.useDelimiter("[,]? ");
while (scanner1.hasNext()) {
// is the next token can be converted to int
if (scanner1.hasNextInt()) {
System.out.println("Found int : " + scanner1.nextInt());
// is the next token can be converted to boolean
} else if (scanner1.hasNextBoolean()) {
System.out.println("Found boolean : " + scanner1.nextBoolean());
// is the next token can be converted to double
} else if (scanner1.hasNextDouble()) {
System.out.println("Found double : " + scanner1.nextDouble());
} else {
System.out.println(scanner1.next());
}
}

result:

Found int : 1
isn't
Found boolean : true
Found int : 0
isn't
Found boolean : false
Found double : 2.0
is
double

0 comments:

 

©2009 Stay the Same | by TNB