Grails(13)Let's Groovy from Java

Grails(13)Let's Groovy from Java
Tutorial 3 Classes and Objects
Objects are collections of related code and data.
A class is a higher level description of an object.

Tutorial 4 Regular expressions basics
Regular Expressions
Regular expressions are the Swiss Army knife of text processing.

"potato" ==~ /potato/         //true

==~ is almost like ==, but it is not saying that they are equal, but check if they are match.

And regular expression is enclosed in /'s.

println "potato" ==~ /potatoe?s?/     //true, ? means maybe.

(ie|ei) means (ie) or (ei).

[abcd]   //means one of the 4

[abcd]? //means one of the 4 or empty

[^abcd] //not a, b, c, d

Regular Expression Operators

println "potato" ==~ /^p.+/      //^ without [] means begin with character p

println "potato" ==~ /.+o$/      //$ at the end means end with o

Tutorial 5 Capturing regex groups
Capture groups
One of the most useful features of Groovy is the ability to use regular expressions to 'capture' data out of a regular expression.


cardnumber = "carl, kiko, 100 12 15 10"
cardRegular = /([a-zA-Z]+), ([a-zA-Z]+), ([0-9]{3}) ([0-9]{2}) ([0-9]{2}) ([0-9]{2})/

matcher = ( cardnumber =~ cardRegular )


if (matcher.matches()) {
    println(matcher.getCount()); //1
    println(matcher[0][1]) //carl
    println(matcher[0][5]) //15
    println(matcher[0][0]) //carl, kiko, 100 12 15 10
}

There are 2 dimension in matcher, we match only once, so there is only one matcher[0]

Non-matching Groups
Here comes an example both working with closure and regular expression.

names = [
     "Carl Luo",
     "YiYi Kang"
]

printClosure = {
    matcher = (it =~ /(.*)(?: .*)* (.*)/);
    if(matcher.matches()){
        println(matcher[0][2] + "," + matcher[0][1])
    }
}

names.each(printClosure);

// Luo Carl
// Kang YiYi

?: is very import here, that means that don't capture the middle group.

Replacement
We do that in Java on java.util.regex.Matcher.

content = "Carl does not like sleep. " +
          "Carl likes to play basketball.";
matcher = (content =~ /Carl/);

content = matcher.replaceAll("Sillycat");

println content   // just change all the names to Sillycat

Reluctant Operators
The operators ?, +, and * are by default "greedy".

Simply add ? after operators to make them reluctant, *?, +? and ??.

Tutorial 6 Groovy SQL
Groovy SQL

language = "Groovy"
println "You should use ${language}"

Groovy interprets anything inside ${} as a groovy expression.

Performing a simple query
sql.eachRow("select * from tableName"){println "$it.id -- ${it.firstName} --" }

Retrieving a single value from DB
row = sql.firstRow('select columnA, columnB from tableName')
println "Row: columnA = ${row.columnA} and column = ${row.columnB}"

Doing more complex queries
firstName = 'first'
lastName = 'last'
sql.execute("insert into people (firstName, lastName) values (${firstName}, ${lastName})")

sql.execute('delete from word where word_id = ?' , [5])

Other Tips
Groovy return the last statement.
def getPersons(){
     def persons = [] //empty list
     sql.eachRow("select * from Person"){
          //persons << it.toRowResult()
          Person p = new Person( it.toRowResult() )
          persons << p
     }
     persons
}

Differences from Java
Default imports
java.io.*
java.lang.*
java.math.BigDecimal
java.math.BigInteger
java.net.*
java.util.*
groovy.lang.*
groovy.util.*

Common gotchas
1. == means equals
2. in is keyword
3. for (int i = 0;i< len; i++) {….}  ====> for (i in 0..len-1)   {…}
                                                         for (i in 0..<len)    { …. }
                                                         len.times { …. }
Things to be aware of
1. semicolons are optional
2. return keyword is optional
3. this keyword means this class in static methods.
4. methods and classes are public by default
5. There is no compile errors before runtime.

Uncommon Gotchas


References:
http://groovy.codehaus.org/Getting+Started+Guide
http://groovy.codehaus.org/Tutorial+3+-+Classes+and+Objects
http://groovy.codehaus.org/Tutorial+4+-+Regular+expressions+basics
http://groovy.codehaus.org/Tutorial+5+-+Capturing+regex+groups
http://groovy.codehaus.org/Tutorial+6+-+Groovy+SQL
http://groovy.codehaus.org/groovy-jdk/
http://groovy.codehaus.org/Differences+from+Java
http://groovy.codehaus.org/Groovy+style+and+language+feature+guidelines+for+Java+developers


猜你喜欢

转载自sillycat.iteye.com/blog/1758696